<?php

defined("IN_IA") or exit("Access Denied");

class yzzc_sunModuleWxapp extends WeModuleWxapp
{
    public function doPageUrl()
    {
        global $_W;
        $url = $_W["attachurl"];
        $this->return_msg(1, $url, "success");
    }

    function return_msg($code = 1, $data = array(), $msg = "success")
    {
        $res["code"] = $code;
        $res["data"] = $data;
        $res["msg"] = $msg;
        exit(json_encode($res));
    }

    /**
     * @param $end_time
     * @param $start_time
     * @return false|float|int
     * 计算天数
     */
    function day($end_time,$start_time)
    {
        $cle = $end_time - $start_time; //得出时间戳差值

        $day = floor($cle / 3600 / 24);
        $hour = floor(($cle % (3600 * 24)) / 3600);  //%取余
        if ($day == 0 && $hour <= 0){
            $this->return_msg(-1,'','还车时间不正确，租期最少大于一小时');
        }
        if ($hour >= 4){
            //大于4小时算一天
            $day+=1;
        }elseif($hour < 4 && $hour > 0){
            //小于4小时 但是大于0 算半天
            $day+=0.5;
        }
        return $day;
    }
    function isOrder($sku_id,$car_num,$e_time,$s_time)
    {
        global $_W;
        $where = " where uniacid = " . $_W["uniacid"];
        if ($sku_id){
            $sku = pdo_get('yzzc_sun_goods_sku',['uniacid'=>$_W['uniacid'],'id'=>$sku_id]);
            if (!$sku){
                $this->return_msg(-1,'','车型不存在！');
            }
            $cid = $sku['goods_id'];
            $where.= " and cid = '{$cid}' and (status = 2 or status = 3) and sku_id = '{$sku_id}'";
            $car_num = $sku['carnum'];
        }else{
            $where.= " and carnum = '{$car_num}'";
        }

        $order = pdo_fetch("select id from " . tablename("yzzc_sun_order") . $where);
        if ($order) {
            $allorder = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and goods_id = {$cid} and sku_id = {$sku_id}");
            foreach ($allorder as $key => $value) {
                $start_time = $value["start_time"];
                $end_time = $value["end_time"];
                $starttime = date("Y-m-d H:i", $start_time);
                $endtime = date("Y-m-d H:i", $end_time);
                if ($s_time < $start_time && $e_time > $end_time && $start_time < $e_time && $s_time < $end_time) {
                    $this->return_msg(-1,'',"您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                } else {
                    if ($s_time < $start_time && $end_time > $e_time && $start_time < $e_time && $s_time < $end_time) {
                        $this->return_msg(-1,'',"您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                    } else {
                        if ($start_time < $s_time && $e_time > $end_time && $start_time < $e_time && $s_time < $end_time) {
                            $this->return_msg(-1,'',"您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                        } else {
                            if ($start_time < $s_time && $end_time > $e_time && $start_time < $e_time && $s_time < $end_time) {
                                $this->return_msg(-1,'',"您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                            } else {
                            }
                        }
                    }
                }
            }
            return true;
        } else {
            $allorder = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and carnum='{$car_num}'");
            foreach ($allorder as $key => $value) {
                $start_time = $value["start_time"];
                $end_time = $value["end_time"];
                $starttime = date("Y-m-d H:i", $start_time);
                $endtime = date("Y-m-d H:i", $end_time);
                if ($s_time < $start_time && $e_time > $end_time && $start_time < $e_time && $s_time < $end_time) {
                    $this->return_msg(-1,'',"您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                } else {
                    if ($s_time < $start_time && $end_time > $e_time && $start_time < $e_time && $s_time < $end_time) {
                        $this->return_msg(-1,'',"您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                    } else {
                        if ($start_time < $s_time && $e_time > $end_time && $start_time < $e_time && $s_time < $end_time) {
                            $this->return_msg(-1,'',"您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                        } else {
                            if ($start_time < $s_time && $end_time > $e_time && $start_time < $e_time && $s_time < $end_time) {
                                $this->return_msg(-1,'',"您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);

                            } else {
                            }
                        }
                    }
                }
            }
            return true;
        }
    }
    function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    function getSign($appid, $msectime)
    {
        $appSecurity = 'Ej3kBb15sBFoEfKoMIj2m8DbWGASN6WP';
        return md5($appid . '&' . $msectime . '&' . $appSecurity);
    }

    /**
     * @param array $elements
     * @param $parentId
     * @return array
     * 处理省市区树型结构
     */
    function buildTree(array $elements, $parentId = null) {
        $branch = [];

        foreach ($elements as $element) {
            if ($element['pid'] == $parentId) {
                $children = $this->buildTree($elements, $element['code']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }
    /**
     * @param $url
     * @param $data
     * @return array
     * 请求API
     */
    function sendPostRequestWithStatusCode($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 设置请求头
        $headers = [
            'Content-Type: application/x-www-form-urlencoded; charset=UTF-8', // 可根据需要设置其他头信息
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'cURL请求错误: ' . curl_error($ch);
        }

        // 获取HTTP状态码
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        // 对返回数据进行JSON解析
        $responseData = json_decode($response, true);

        return ['statusCode' => $statusCode, 'data' => $responseData];
    }

    function scoreAct($uid, $type = 1, $score = 0)
    {
        global $_W;
        $data["uniacid"] = $_W["uniacid"];
        $data["uid"] = $uid;
        $data["type"] = $type;
        $data["score"] = $score;
        $data["createtime"] = time();
        pdo_insert("yzzc_sun_integral_log", $data);
        if ($score > 0) {
            pdo_update("yzzc_sun_user", array("all_integral +=" => $data["score"]), array("id" => $data["uid"]));
        }
        pdo_update("yzzc_sun_user", array("now_integral +=" => $data["score"]), array("id" => $data["uid"]));
    }

    public function wxPay($options = array())
    {
        $data["appid"] = $options["appid"];
        $data["mch_id"] = $options["mch_id"];
        $data["openid"] = $options["openid"];
        $data["nonce_str"] = $this->randstr();
        $data["body"] = $options["body"];
        $data["attach"] = $options["attach"];
        $data["out_trade_no"] = $options["out_trade_no"];
        $data["notify_url"] = $options["notify_url"];
        $data["total_fee"] = $options["total_fee"] * 100;
        $data["spbill_create_ip"] = $_SERVER["REMOTE_ADDR"];
        $data["trade_type"] = "JSAPI";
        $data["time_start"] = $options["time_start"];
        $data["time_expire"] = $options["time_expire"];
        ksort($data, SORT_STRING);
        $string = '';
        foreach ($data as $key => $v) {
            if (!empty($v)) {
                $string .= "{$key}={$v}&";
            } else {
            }
        }
        $string .= "key=" . $options["pay_key"] . '';
        $data["sign"] = strtoupper(md5($string));
        $xmlData = array2xml($data);
        $response = $this->https_request("https://api.mch.weixin.qq.com/pay/unifiedorder", $xmlData);
        $result = json_decode(json_encode(simplexml_load_string($response, "SimpleXMLElement", LIBXML_NOCDATA)), true);
        if ($result["return_code"] == "SUCCESS") {
            $payData["appId"] = $data["appid"];
            $payData["timeStamp"] = (string)time();
            $payData["nonceStr"] = $this->randstr();
            $payData["package"] = "prepay_id=" . $result["prepay_id"];
            $payData["signType"] = "MD5";
            $payString = '';
            ksort($payData, SORT_STRING);
            foreach ($payData as $key => $v) {
                $payString .= "{$key}={$v}&";
            }
            $payString .= "key=" . $options["pay_key"] . '';
            $payData["paySign"] = strtoupper(md5($payString));
            $payData["return_code"] = $result["return_code"];
        } else {
            $payData["return_code"] = $result["return_code"];
            $payData["return_msg"] = $result["return_msg"];
        }
        return $payData;
    }

    public function testpay()
    {
        $appid = '';
        $mch_id = '';
        $options = array("body" => "测试", "appid" => $appid, "mch_id" => $mch_id, "out_trade_no" => time(), "attach" => json_encode(array("a" => 1)), "notify_url" => "http://" . $_SERVER["HTTP_HOST"] . "/ticket/Appletpay/notify", "total_fee" => 0.01, "spbill_create_ip" => $_SERVER["REMOTE_ADDR"], "openid" => "oLWoc0X0guzZ89lxWdL57Z7mz4r4");
        $data = $this->wxPay($options);
        return common_json("success", 0, $data);
    }

    public function notify()
    {
        $json = $_POST;
        $xml = file_get_contents("php://input");
        $data = json_decode(json_encode(simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA)), true);
        $arraySign = $data["sign"];
        unset($data["sign"]);
        ksort($data, SORT_STRING);
        $string = '';
        foreach ($data as $key => $v) {
            $string .= "{$key}={$v}&";
        }
        $arr = json_decode($data["attach"], true);
        $pay_key = '';
        $string .= "key=" . $pay_key;
        $sign = strtoupper(md5($string));
        if ($arraySign == $sign) {
            exit("SUCCESS");
        } else {
            exit("FAIL");
        }
    }

    function randstr($length = 20)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = '';
        $i = 0;
        while ($i < $length) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            $i++;
        }
        return $str;
    }

    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_SSLVERSION, 4);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function doPageOpenid()
    {
        global $_W, $_GPC;
        $res = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
        $code = $_GPC["code"];
        $appid = $res["appid"];
        $secret = $res["appsecret"];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        function httpRequest($url, $data = null)
        {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }

        $re = httpRequest($url);
        $opendata = json_decode($re);
        $openid = $opendata->openid;
        $res = pdo_get("yzzc_sun_user", array("openid" => $openid, "uniacid" => $_W["uniacid"]));
        if ($res) {
            $res["session_key"] = $opendata->session_key;
            $this->return_msg(1, $res, "success");
        } else {
            $data = array();
            $data["openid"] = $openid;
            $data["user_name"] = "访客" . rand(10000, 99999);
            $data["uniacid"] = $_W["uniacid"];
            $data["time"] = time();
            $res2 = pdo_insert("yzzc_sun_user", $data);
            $user = pdo_get("yzzc_sun_user", array("openid" => $openid, "uniacid" => $_W["uniacid"]));
            $user["session_key"] = $opendata->session_key;
            $this->return_msg(1, $user, "success");
        }
    }

    public function doPageLoginOpenid()
    {
        global $_W, $_GPC;
        $res = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
        $code = $_GPC["code"];
        $appid = $res["appid"];
        $secret = $res["appsecret"];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        function httpRequest($url, $data = null)
        {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            if (!empty($data)) {
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }

        $re = httpRequest($url);
        $opendata = json_decode($re);
        $openid = $opendata->openid;
        $res = pdo_get("yzzc_sun_user", array("openid" => $openid, "uniacid" => $_W["uniacid"]));
        if ($res) {
            $res["session_key"] = $opendata->session_key;
            $this->return_msg(1, $res, "success");
        } else {
            $data = array();
            $data["openid"] = $openid;
            $data["user_name"] = "访客" . rand(10000, 99999);
            $data["uniacid"] = $_W["uniacid"];
            $data["time"] = time();
            $res2 = pdo_insert("yzzc_sun_user", $data);
            $user = pdo_get("yzzc_sun_user", array("openid" => $openid, "uniacid" => $_W["uniacid"]));
            $user["session_key"] = $opendata->session_key;
            $this->return_msg(1, $user, "success");
        }
    }


    /**
     * @return false|mixed
     * 获取小程序token
     */
    public function getAccessToken(){
        global $_W;
        $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
        $appid = $appData["appid"];
        $appSecret = $appData["appsecret"];
        $requestUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
        $requestUrl = sprintf($requestUrl, $appid, $appSecret);
        $data = $this->httpRequest($requestUrl);  // 发起获取 access_token 请求
        $data = json_decode($data,true);
        if (!empty($data['access_token'])) {
            return $data['access_token'];
        } else {
            return false;
        }
    }


    function getSessionKey(string $code)
    {
        global $_W;
        $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
        $appid = $appData["appid"];
        $appSecret = $appData["appsecret"];
        $url = strtr('https://api.weixin.qq.com/sns/jscode2session?appid={APPID}&secret={SECRET}&js_code={JSCODE}&grant_type=authorization_code', [
            '{APPID}' => $appid,
            '{SECRET}' => $appSecret,
            '{JSCODE}' => $code,
        ]);
        $result = $this->https_request($url);
        $result = json_decode($result,true);
        if (!empty($result['errcode'])) {
            $this->return_msg(-1,[],"小程序登录错误信息：{$result['errmsg']}");
        }
        return $result;
    }

    /**
     * @return void
     * 获取openid
     */
    public function doPagegetOpenid(){
        global $_W,$_GPC;
        $code = $_GPC['code'];
        if (!$code){
            $this->return_msg(-1,[],'code不存在');
        }

        $openid = $this->getSessionKey($_GPC['code']);
        $this->return_msg(1,['openid'=>$openid['openid']],'操作成功');
    }
    /**
     * @return array|bool|string
     * 获取手机号
     */
    function GetUserPhoneNumber($code){
        global $_W,$_GPC;
        $token = $this->getAccessToken();
        if (!$token) {
            return [];
        }
        if (!$code){
            $this->return_msg(-1,[],'code不存在');
        }

        $url = strtr('https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={TOKEN}', ['{TOKEN}' => $token]);
        $result = $this->httpRequest($url,['code'=>$code]);
        $result = json_decode($result,true);
        if (!empty($result['errcode'])) {
            $this->return_msg(-1,'',"小程序登录错误信息：{$result['errmsg']} --- {$result['errcode']}");
        }
        return $result['phone_info']['phoneNumber'];
    }

    /**
     * @return void
     * 登录
     */
    public function doPageLogin()
    {
//        global $_W,$_GPC;
//        $code = trim($_GPC['code']);
//        $rawData = trim($_GPC['rawData']);
//        $signature = trim($_GPC['signature']);
//        $iv = trim($_GPC['iv']);
//        $encryptedData = trim($_GPC['encryptedData']);
////        if (!$code || !$rawData || !$signature || !$iv || !$encryptedData){
////            $this->return_msg(-1,[],'参数不全');
////        }
//        $sessionKeyData = $this->getSessionKey($code);
//        if (!$sessionKeyData) {
//            $this->return_msg(-1,[],'小程序登录错误信息：签名错误！');
//        }
////        if (sha1($rawData . $sessionKeyData['session_key']) != $signature) {
////            $this->return_msg(-1,[],'小程序登录错误信息：签名错误！');
////        }
//        $sessionKey = base64_decode($sessionKeyData['session_key']);
//        dd($sessionKey,$sessionKeyData);
//        $iv = base64_decode($iv);
//        $encryptedData = base64_decode($encryptedData);
//
//        $decryptData = openssl_decrypt($encryptedData, 'AES-128-CBC', $sessionKey, 1, $iv);
//
//        if (empty($decryptData)) {
//            $this->return_msg(-1,[],'小程序登录错误信息：解密出错！');
//        }
//        $data = json_decode($decryptData, JSON_UNESCAPED_UNICODE);
//        dd(array_merge($data, $sessionKeyData));

        global $_GPC, $_W;
        $code = $_GPC["code"];
        $phoneCode = $_GPC['phoneCode'];
        if (!$code || !$phoneCode){
            $this->return_msg(-1,[],'参数不全');
        }

        $openid = $this->getSessionKey($code);
        $res = pdo_get("yzzc_sun_user", array("openid" => $openid['openid'], "uniacid" => $_W["uniacid"]));
        if ($res) {
            $data["openid"] = $openid['openid'];
            $data["user_name"] = '微信用户';
            if (isset($_GPC['parents_id']) && $_GPC['parents_id'] && !$res['parents_id']){
                $parents = pdo_get("yzzc_sun_user", array("id" => $_GPC['parents_id'], "uniacid" => $_W["uniacid"]));
                $data['parents_id'] = $_GPC['parents_id'];
                $data['parents_name'] = $parents['user_name'];
            }
            $data['user_tel'] = $this->GetUserPhoneNumber($phoneCode);
            pdo_update("yzzc_sun_user", $data, array("openid" => $openid['openid'], "uniacid" => $_W["uniacid"]));
            $user = pdo_get("yzzc_sun_user", array("openid" => $openid['openid'], "uniacid" => $_W["uniacid"]));
            $this->return_msg(1, $user);
        } else {
            $data["openid"] = $openid['openid'];
            $data["user_name"] = '微信用户';
            $data["uniacid"] = $_W["uniacid"];
            $data["time"] = time();
            $data['user_tel'] = $this->GetUserPhoneNumber($phoneCode);

            if (isset($_GPC['parents_id']) && $_GPC['parents_id']){
                $parents = pdo_get("yzzc_sun_user", array("id" => $_GPC['parents_id'], "uniacid" => $_W["uniacid"]));
                $data['parents_id'] = $_GPC['parents_id'];
                $data['parents_name'] = $parents['user_name'];
            }
            pdo_insert("yzzc_sun_user", $data);
            $user = pdo_get("yzzc_sun_user", array("openid" => $openid['openid'], "uniacid" => $_W["uniacid"]));
            $this->return_msg(1, $user);
        }
    }
    public function doPageShouye()
    {
        global $_GPC, $_W;
        $guoqi = pdo_getall("yzzc_sun_xzorder", array("uniacid" => $_W["uniacid"], "ispay" => 0));
        foreach ($guoqi as $key => $value) {
            if ($value["createtime"] + 500 < time()) {
                $guoqi1 = pdo_delete("yzzc_sun_xzorder", array("uniacid" => $_W["uniacid"], "id" => $value["id"]));
            }
        }
        $banner = pdo_get("yzzc_sun_banner", array("uniacid" => $_W["uniacid"]), array("lb_imgs"));
        $res["banner"] = explode(",", $banner["lb_imgs"]);
        $res["icon"] = pdo_get("yzzc_sun_logoset", array("uniacid" => $_W["uniacid"]));
        $res["index_haibao_pic"] = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]), array("index_haibao_pic"));
        $system = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]), array("is_open_car", "open_ys"));
        $res["is_open_car"] = $system["is_open_car"];
        $res["open_ys"] = $system["open_ys"];
        $filed = array("id", "pic", "moneytype", "money", "name");
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        if ($system["open_ys"] == 1) {
            if ($_GPC["state"] == 1) {
                if ($_GPC["sort"] == "distance") {
                    $start = ($page - 1) * $length;
                    $lat = $_GPC["lat"] ? $_GPC["lat"] : 0;
                    $lng = $_GPC["lng"] ? $_GPC["lng"] : 0;
                    if ($lat > 0 && $lng > 0) {
                        $sql = "select a.id,a.pic,b.lng,b.lat,a.moneytype,a.money,a.name,( 6371 * acos (    \n                        cos ( radians(" . $lat . ") )    \n                        * cos( radians( b.lat ) )    \n                        * cos( radians( b.lng ) - radians(" . $lng . ") )    \n                        + sin ( radians(" . $lat . ") )    \n                        * sin( radians( b.lat ) )    )    \n                        ) AS distance from " . tablename("yzzc_sun_goods") . "a " . "left join" . tablename("yzzc_sun_branch") . "b on b.id=a.sid \n                    where a.rec =1 and a.status =1 and a.is_del = 0 and b.status = 1 and a.uniacid = " . $_W["uniacid"] . " order by distance asc,a.id desc limit " . $start . "," . $length;
                        $list = pdo_fetchall($sql);
                        $res["car"] = $list;
                    } else {
                        $this->return_msg(-1, array(), "请先定位");
                    }
                } else {
                    $res["car"] = pdo_getall("yzzc_sun_goods", array("uniacid" => $_W["uniacid"], "status" => 1, "rec" => 1, "is_del" => 0), $filed, '', "id desc", array($page, $length));
                }
            } else {
                $start = ($page - 1) * $length;
                $res["car"] = pdo_fetchall("select * from " . tablename("yzzc_sun_car") . " where uniacid =" . $_W["uniacid"] . " and status = 2 and rec = 1 and is_del = 0 order by sort asc limit " . $start . "," . $length);
            }
        } else {
            $start = ($page - 1) * $length;
            if ($_GPC["sort"] == "distance") {
                $lat = $_GPC["lat"] ? $_GPC["lat"] : 0;
                $lng = $_GPC["lng"] ? $_GPC["lng"] : 0;
                if ($lat > 0 && $lng > 0) {
                    $sql = "select a.id,a.pic,b.lng,b.lat,a.moneytype,a.money,a.name,( 6371 * acos (    \n                    cos ( radians(" . $lat . ") )    \n                    * cos( radians( b.lat ) )    \n                    * cos( radians( b.lng ) - radians(" . $lng . ") )    \n                    + sin ( radians(" . $lat . ") )    \n                    * sin( radians( b.lat ) )    )    \n                    ) AS distance from " . tablename("yzzc_sun_goods") . "a " . "left join" . tablename("yzzc_sun_branch") . "b on b.id=a.sid \n                where a.rec =1 and a.status =1 and a.is_del = 0 and b.status = 1 and a.uniacid = " . $_W["uniacid"] . " order by distance asc,a.id desc limit " . $start . "," . $length;
                    $list = pdo_fetchall($sql);
                    $res["car"] = $list;
                } else {
                    $this->return_msg(-1, array(), "请先定位");
                }
            } else {
                $res["car"] = pdo_getall("yzzc_sun_goods", array("uniacid" => $_W["uniacid"], "status" => 1, "rec" => 1, "is_del" => 0), $filed, '', "id desc", array($page, $length));
            }
            $res["ershoucar"] = pdo_fetchall("select * from " . tablename("yzzc_sun_car") . " where uniacid =" . $_W["uniacid"] . " and status = 2 and rec = 1 and is_del = 0 order by sort asc limit " . $start . "," . $length);
        }
        $this->return_msg(1, $res, "success");
    }

    public function doPagegetcity()
    {
        global $_GPC, $_W;
        $city_id = $_GPC["city_id"];
        $uid = $_GPC["uid"];
        if ($city_id) {
            $nowcity = pdo_get("yzzc_sun_carcity", array("uniacid" => $_W["uniacid"], "id" => $city_id));
            $res["nowcity"] = $nowcity;
        }
        $reccity = pdo_getall("yzzc_sun_carcity", array("uniacid" => $_W["uniacid"], "rec" => 1), array(), '', "zimu asc");
        $res["reccity"] = $reccity;
        $usercity = pdo_fetchall("select a.name,a.id from " . tablename("yzzc_sun_carcity") . "a left join " . tablename("yzzc_sun_usercity") . "b on b.city_id = a.id where b.uid = {$uid} and a.uniacid = " . $_W["uniacid"] . " and b.uniacid = " . $_W["uniacid"] . " order by b.time desc");
        $res["usercity"] = $usercity;
        $city = pdo_getall("yzzc_sun_carcity", array("uniacid" => $_W["uniacid"]), array(), '', "zimu asc");
        $city = $this->dataGroup($city, "zimu");
        $res["city"] = $city;
        $this->return_msg(1, $res, "success");
    }

    public function doPagegetbrand()
    {
        global $_GPC, $_W;
        $brand_id = $_GPC["brand_id"];
        if ($brand_id) {
            $nowbrand = pdo_get("yzzc_sun_carbrand", array("uniacid" => $_W["uniacid"], "id" => $brand_id));
            $res["nowbrand"] = $nowbrand;
        }
        $brand = pdo_getall("yzzc_sun_carbrand", array("uniacid" => $_W["uniacid"]), array(), '', "zimu asc");
        $brand = $this->dataGroup($brand, "zimu");
        $res["brand"] = $brand;
        $this->return_msg(1, $res, "success");
    }

    public function dataGroup($dataArr, $keyStr)
    {
        $newArr = [];
        foreach ($dataArr as $k => $val) {
            $newArr[$val[$keyStr]][] = $val;
        }
        return $newArr;
    }

    public function doPagechoosecity()
    {
        global $_GPC, $_W;
        $uid = $_GPC["uid"];
        $city_id = $_GPC["city_id"];
        $res = pdo_get("yzzc_sun_usercity", array("uniacid" => $_W["uniacid"], "uid" => $uid, "city_id" => $city_id));
        if ($res) {
            $data["time"] = time();
            $result = pdo_update("yzzc_sun_usercity", $data, array("uniacid" => $_W["uniacid"], "id" => $res["id"]));
        } else {
            $city = pdo_getall("yzzc_sun_usercity", array("uniacid" => $_W["uniacid"], "uid" => $uid), array(), '', "time asc");
            if (count($city) < 3) {
                $data["uid"] = $uid;
                $data["city_id"] = $city_id;
                $data["uniacid"] = $_W["uniacid"];
                $data["time"] = time();
                $result = pdo_insert("yzzc_sun_usercity", $data);
            } else {
                pdo_delete("yzzc_sun_usercity", array("uniacid" => $_W["uniacid"], "id" => $city["0"]["id"]));
                $data["uid"] = $uid;
                $data["city_id"] = $city_id;
                $data["uniacid"] = $_W["uniacid"];
                $data["time"] = time();
                $result = pdo_insert("yzzc_sun_usercity", $data);
            }
        }
    }

    public function doPageuserdcarlist()
    {
        global $_GPC, $_W;
        $where = " where uniacid = " . $_W["uniacid"] . " and status = 2 and is_del = 0 ";
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        $start = ($page - 1) * $length;
        $limit = "limit " . $start . "," . $length;
        $sort = $_GPC["sort"];
        $city_id = $_GPC["city_id"];
        if ($city_id != 0) {
            $where .= " and carcity = " . $city_id;
        }
        $brand_id = $_GPC["brand_id"];
        if ($brand_id != 0) {
            $where .= " and carbrand = " . $brand_id;
        }
        $carnum = $_GPC["carnum"];
        if ($carnum) {
            $where .= " and carnum like '%{$carnum}%'";
        }
        if ($sort == 1) {
            $order = " order by sort asc ";
        } else {
            if ($sort == 2) {
                $order = " order by money desc ";
            } else {
                if ($sort == 3) {
                    $order = " order by money asc ";
                } else {
                    if ($sort == 4) {
                        $order = " order by registrationtime desc ";
                    } else {
                        if ($sort == 5) {
                            $order = " order by mileage asc ";
                        } else {
                        }
                    }
                }
            }
        }
        $res = pdo_fetchall("select * from " . tablename("yzzc_sun_car") . $where . $order . $limit);
        foreach ($res as $key => $value) {
            $res[$key]["registrationtime"] = date("Y年m月", $value["registrationtime"]);
        }
        $this->return_msg(1, $res, "success");
    }

    public function doPageuserdcar()
    {
        global $_GPC, $_W;
        $id = $_GPC["id"];
        $res = pdo_get("yzzc_sun_car", array("uniacid" => $_W["uniacid"], "id" => $id, "status" => 2, "is_del" => 0));
        $res["registrationtime"] = date("Y年m月", $res["registrationtime"]);
        $res["carcity"] = pdo_get("yzzc_sun_carcity", array("uniacid" => $_W["uniacid"], "id" => $res["carcity"]), array("name"))["name"];
        $res["imgs"] = explode(",", $res["imgs"]);
        $this->return_msg(1, $res, "success");
    }

    public function rec()
    {
        global $_GPC, $_W;
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        $start = ($page - 1) * $length;
        $lat = $_GPC["lat"] ? $_GPC["lat"] : 0;
        $lng = $_GPC["lng"] ? $_GPC["lng"] : 0;
        if ($lat > 0 && $lng > 0) {
            $sql = "select a.id,a.pic,b.lng,b.lat,a.moneytype,a.money,a.name,( 6371 * acos (    \n                cos ( radians(" . $lat . ") )    \n                * cos( radians( b.lat ) )    \n                * cos( radians( b.lng ) - radians(" . $lng . ") )    \n                + sin ( radians(" . $lat . ") )    \n                * sin( radians( b.lat ) )    )    \n                ) AS distance from " . tablename("yzzc_sun_goods") . "a " . "left join" . tablename("yzzc_sun_branch") . "b on b.id=a.sid \n            where a.rec =1 and a.status =1 and a.is_del = 0 and b.status = 1 and a.uniacid = " . $_W["uniacid"] . " order by distance asc limit " . $start . "," . $length;
            $list = pdo_fetchall($sql);
            var_dump($list);
            exit;
        } else {
            $this->return_msg(-1, array(), "请先定位");
        }
    }

    public function doPageuserdrive()
    {
        global $_W, $_GPC;
        $uid = $_GPC["uid"];
        $sql = "SELECT * FROM " . tablename("yzzc_sun_user_drive") . " where uid = " . $uid . " ORDER BY id DESC";
        $res = pdo_fetchall($sql);
        $this->return_msg(1, $res, "success");
    }

    public function doPageuserdriveset()
    {
        global $_W, $_GPC;
        $set = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("zj"));
        $zj = explode(",", $set["zj"]);
        $sfcode = 0;
        $sfimg = 0;
        $jsimg = 0;
        $zpimg = 0;
        if (in_array("0", $zj)) {
            $sfcode = 1;
        }
        if (in_array("1", $zj)) {
            $sfimg = 1;
        }
        if (in_array("2", $zj)) {
            $jsimg = 1;
        }
        if (in_array("3", $zj)) {
            $zpimg = 1;
        }
        $info = array("sfcode" => $sfcode, "sfimg" => $sfimg, "jsimg" => $jsimg, "zpimg" => $zpimg);
        $this->return_msg(1, $info, "success");
    }

    public function doPageEdituserdriveInfo()
    {
        global $_GPC, $_W;
        $info = pdo_get("yzzc_sun_user_drive", array("uniacid" => $_W["uniacid"], "id" => $_GPC["id"]));
        $this->return_msg(1, $info, "success");
    }

    public function doPageEdituserdrive()
    {
        global $_W, $_GPC;
        $set = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]));
        $zj = explode(",", $set["zj"]);
        $data["uid"] = $_GPC["uid"];
        $data["name"] = $_GPC["name"];
        $data["phone"] = $_GPC["phone"];
        if (in_array("0", $zj)) {
            if (empty($_GPC["sfcode"])) {
                $this->return_msg(-1, array(), "请输入驾驶员身份证号码");
            }
            $data["sfcode"] = $_GPC["sfcode"];
        }
        if (in_array("1", $zj)) {
            if (empty($_GPC["sfimg"]) || empty($_GPC["sfimgfan"])) {
                $this->return_msg(-1, array(), "请上传身份证正反面照片");
            }
            $data["sfimg"] = $_GPC["sfimg"];
            $data["sfimgfan"] = $_GPC["sfimgfan"];
        }
        if (in_array("2", $zj)) {
            if (empty($_GPC["jsimg"]) || empty($_GPC["jsimgfan"])) {
                $this->return_msg(-1, array(), "请上传驾驶证正面和附页照片");
            }
            $data["jsimg"] = $_GPC["jsimg"];
            $data["jsimgfan"] = $_GPC["jsimgfan"];
        }
        if (in_array("3", $zj)) {
            if (empty($_GPC["zpimg"])) {
                $this->return_msg(-1, array(), "请上传手持身份证自拍照片");
            }
            $data["zpimg"] = $_GPC["zpimg"];
        }
        $data["time"] = time();
        $data["uniacid"] = $_W["uniacid"];
        $res = pdo_update("yzzc_sun_user_drive", $data, array("uniacid" => $_W["uniacid"], "id" => $_GPC["driveid"]));
        if ($res) {
            $this->return_msg(1, array(), "success");
        } else {
            $this->return_msg(-1, array(), "添加失败！");
        }
    }


    public function doPageAdduserdrive()
    {
        global $_W, $_GPC;
        $set = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]));
        $zj = explode(",", $set["zj"]);
        $data["uid"] = $_GPC["uid"];
        $data["name"] = $_GPC["name"];
        $data["phone"] = $_GPC["phone"];
        if (in_array("0", $zj)) {
            if (empty($_GPC["sfcode"])) {
                $this->return_msg(-1, array(), "请输入驾驶员身份证号码");
            }
            $data["sfcode"] = $_GPC["sfcode"];
        }
        if (in_array("1", $zj)) {
            if (empty($_GPC["sfimg"]) || empty($_GPC["sfimgfan"])) {
                $this->return_msg(-1, array(), "请上传身份证正反面照片");
            }
            $data["sfimg"] = $_GPC["sfimg"];
            $data["sfimgfan"] = $_GPC["sfimgfan"];
        }
        if (in_array("2", $zj)) {
            if (empty($_GPC["jsimg"]) || empty($_GPC["jsimgfan"])) {
                $this->return_msg(-1, array(), "请上传驾驶证正面和附页照片");
            }
            $data["jsimg"] = $_GPC["jsimg"];
            $data["jsimgfan"] = $_GPC["jsimgfan"];
        }
        if (in_array("3", $zj)) {
            if (empty($_GPC["zpimg"])) {
                $this->return_msg(-1, array(), "请上传手持身份证自拍照片");
            }
            $data["zpimg"] = $_GPC["zpimg"];
        }
        $data["time"] = time();
        $data["uniacid"] = $_W["uniacid"];
        $res = pdo_insert("yzzc_sun_user_drive", $data);
        if ($res) {
            $this->return_msg(1, array(), "success");
        } else {
            $this->return_msg(-1, array(), "添加失败！");
        }
    }

    public function doPagechoosedrive()
    {
        global $_W, $_GPC;
        $id = $_GPC["id"];
        $uid = $_GPC["uid"];
        pdo_update("yzzc_sun_user_drive", array("is_mr" => 0), array("uniacid" => $_W["uniacid"], "uid" => $uid));
        $res = pdo_update("yzzc_sun_user_drive", array("is_mr" => 1), array("uniacid" => $_W["uniacid"], "id" => $id));
        if ($res) {
            $this->return_msg(1, array(), "设置成功");
        } else {
            $this->return_msg(-1, array(), "设置失败");
        }
    }

    public function doPagedeluserdrive()
    {
        global $_W, $_GPC;
        $id = $_GPC["id"];
        $info = pdo_get("yzzc_sun_user_drive", array("uniacid" => $_W["uniacid"], "id" => $_GPC["id"]));
        $res = pdo_delete("yzzc_sun_user_drive", array("uniacid" => $_W["uniacid"], "id" => $id));
        if ($res) {
            if ($info["sfimg"]) {
                unlink("../attachment/" . $info["sfimg"]);
            }
            if ($info["jsimg"]) {
                unlink("../attachment/" . $info["jsimg"]);
            }
            if ($info["sfimgfan"]) {
                unlink("../attachment/" . $info["sfimgfan"]);
            }
            if ($info["jsimgfan"]) {
                unlink("../attachment/" . $info["jsimgfan"]);
            }
            if ($info["zpimg"]) {
                unlink("../attachment/" . $info["zpimg"]);
            }
            $this->return_msg(1, array(), "删除成功");
        } else {
            $this->return_msg(-1, array(), "删除失败");
        }
    }

    public function doPageToupload()
    {
        $uptypes = array("image/jpg", "image/jpeg", "image/png", "image/pjpeg", "image/gif", "image/bmp", "image/x-png");
        $max_file_size = 4000000;
        $destination_folder = "../attachment/";
        $watermark = 2;
        $watertype = 1;
        $waterposition = 1;
        $waterstring = "666666";
        $imgpreview = 1;
        $imgpreviewsize = 1 / 2;
        if (!is_uploaded_file($_FILES["file"]["tmp_name"])) {
            echo "图片不存在!";
            exit;
        }
        $file = $_FILES["file"];
        if ($max_file_size < $file["size"]) {
            echo "文件太大!";
            exit;
        }
        if (!in_array($file["type"], $uptypes)) {
            echo "文件类型不符!" . $file["type"];
            exit;
        }
        if (!file_exists($destination_folder)) {
            mkdir($destination_folder);
        }
        $filename = $file["tmp_name"];
        $image_size = getimagesize($filename);
        $pinfo = pathinfo($file["name"]);
        $ftype = $pinfo["extension"];
        $destination = $destination_folder . str_shuffle(rand(11111, 99999) . time() . rand(111111, 999999)) . "." . $ftype;
        if (file_exists($destination) && $overwrite != true) {
            echo "同名文件已经存在了";
            exit;
        }
        if (!move_uploaded_file($filename, $destination)) {
            echo "移动文件出错";
            exit;
        }
        $pinfo = pathinfo($destination);
        $fname = $pinfo["basename"];
        if ($watermark == 1) {
            $iinfo = getimagesize($destination, $iinfo);
            $nimage = imagecreatetruecolor($image_size[0], $image_size[1]);
            $white = imagecolorallocate($nimage, 255, 255, 255);
            $black = imagecolorallocate($nimage, 0, 0, 0);
            $red = imagecolorallocate($nimage, 255, 0, 0);
            imagefill($nimage, 0, 0, $white);
            switch ($iinfo[2]) {
                case 1:
                    $simage = imagecreatefromgif($destination);
                    break;
                case 2:
                    $simage = imagecreatefromjpeg($destination);
                    break;
                case 3:
                    $simage = imagecreatefrompng($destination);
                    break;
                case 6:
                    $simage = imagecreatefromwbmp($destination);
                    break;
                default:
                    die("不支持的文件类型");
            }
            imagecopy($nimage, $simage, 0, 0, 0, 0, $image_size[0], $image_size[1]);
            imagefilledrectangle($nimage, 1, $image_size[1] - 15, 80, $image_size[1], $white);
            switch ($watertype) {
                case 1:
                    imagestring($nimage, 2, 3, $image_size[1] - 15, $waterstring, $black);
                    break;
                case 2:
                    $simage1 = imagecreatefromgif("xplore.gif");
                    imagecopy($nimage, $simage1, 0, 0, 0, 0, 85, 15);
                    imagedestroy($simage1);
                    break;
            }
            switch ($iinfo[2]) {
                case 1:
                    imagejpeg($nimage, $destination);
                    break;
                case 2:
                    imagejpeg($nimage, $destination);
                    break;
                case 3:
                    imagepng($nimage, $destination);
                    break;
                case 6:
                    imagewbmp($nimage, $destination);
                    break;
            }
            imagedestroy($nimage);
            imagedestroy($simage);
        }
        echo $fname;
        @(require_once IA_ROOT . "/framework/function/file.func.php");
        @($filename = $fname);
        @file_remote_upload($filename);
    }

    public function doPageNavset()
    {
        global $_W;
        $res = pdo_get("yzzc_sun_logoset", array("uniacid" => $_W["uniacid"]));
        $this->return_msg(1, $res, "success");
    }

    public function doPageSupport()
    {
        global $_W;
        $field = array("sup_logo", "sup_name", "sup_tel");
        $res = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]), $field);
        $this->return_msg(1, $res, "success");
    }

    public function doPageColor()
    {
        global $_W;
        $field = array("top_font_color", "top_color", "foot_color", "foot_font_color_one", "foot_font_color_two", "open_fj");
        $res = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]), $field);
        $this->return_msg(1, $res, "success");
    }

    public function doPageAdpic()
    {
        global $_W;
        $res = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]), "ad_pic");
        if ($res["ad_pic"] == 1) {
            $res = pdo_getall("yzzc_sun_adpic", array("uniacid" => $_W["uniacid"]), array(), '', array("sort asc"));
        } else {
            $res = array();
        }
        $this->return_msg(1, $res, "success");
    }

    public function doPageSign()
    {
        global $_GPC, $_W;
        if (empty($_GPC["uid"])) {
            $this->return_msg(-999, array(), "uid不能为空");
        } else {
            $today = strtotime(date("Y-m-d", time()));
            $issign = pdo_get("yzzc_sun_signlog", array("uid" => $_GPC["uid"], "createtime >=" => $today));
            if ($issign) {
                $this->return_msg(-1, array(), "今天已经签到了哦");
            }
            $integral = pdo_get("yzzc_sun_integralset", array("uniacid" => $_W["uniacid"]), array("sign"));
            if ($integral["sign"] > 0) {
                $this->scoreAct($_GPC["uid"], 1, $integral["sign"]);
            }
            $data["uniacid"] = $_W["uniacid"];
            $data["uid"] = $_GPC["uid"];
            $data["score"] = $integral["sign"];
            $data["createtime"] = time();
            $res = pdo_insert("yzzc_sun_signlog", $data);
            if ($res) {
                $this->return_msg(1, array("score" => $data["score"]), "签到成功");
            } else {
                $this->return_msg(-1, array(), "签到失败");
            }
        }
    }

    /**
     * @return void
     * 会员资料
     */
    public function doPageUsers()
    {
        global $_GPC, $_W;
        if ($_GPC["uid"]) {
            $res["user"] = pdo_get("yzzc_sun_user", array("uniacid" => $_W["uniacid"], "id" => $_GPC["uid"]));
            if (!$res["user"]){
                $this->return_msg(-1, [],'会员未注册，请先注册');
            }
            $res["couponnum"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_coupon_get") . "where uid =" . $_GPC["uid"] . " and type = 2 and isuse = 0");
            $res["rentnum"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_coupon_get") . "where uid =" . $_GPC["uid"] . " and type = 1 ");
            $drive = pdo_get('yzzc_sun_user_drive',array("uniacid" => $_W["uniacid"], "uid" => $_GPC["uid"]));
            $res['drive'] = $drive === false ? [] : $drive;

            //门店身份
//            $is_branch = 0;
//            if ($branch_admin){
//                $is_branch = 1;
//            }
            $branch_admin = pdo_get('yzzc_sun_branch_admin',['uid'=>$_GPC["uid"]]);
            $res['branch'] = $branch_admin === false ? [] :$branch_admin;

            //交换车
            $shuttle = pdo_get('yzzc_sun_shuttle',['uid'=>$_GPC["uid"]]);
            $res['shuttle'] = $shuttle === false ? [] : $shuttle;

            //申请资料
            $user_store = pdo_get('yzzc_sun_store_apply',['uid'=>$_GPC['uid'],"uniacid" => $_W["uniacid"]]);
            if ($user_store){
                $user_store["province_name"] = $this->getcode($user_store["province"])["fullname"];
                $user_store["city_name"] = $this->getcode($user_store["city"])["fullname"];
                $user_store["area_name"] = $this->getcode($user_store["area"])["fullname"];
//                $res['apply_store'] = 1;
                $res['apply_info'] = $user_store;
                $res['apply_order'] = pdo_get('yzzc_sun_store_order',['store_id'=>$user_store['store_id'],"uniacid" => $_W["uniacid"],'member_id'=>0],['order_id','amount','pay_status','order_no']);
                if ($user_store['status'] == 1){
                    //审核通过
                    $branch_info = pdo_get('yzzc_sun_branch',['store_id'=>$user_store['store_id']]);
                    $res["user"]['member_status'] = $branch_info['member_status'];
                    $res["user"]['member_start_time'] = $branch_info['member_start_time'];
                    $res["user"]['member_end_time'] = $branch_info['member_end_time'];
                }
            }else{
//                $res['apply_store'] = 0;
            }

            //判断是不是销售
            $distribution = pdo_get("yzzc_sun_distribution_promoter", array("uniacid" => $_W['uniacid'], "openid" => $res["user"]));
            if (!$distribution){
                $distribution = [];
            }
            $res['distribution'] = $distribution;

            //判断是不是个人车主
            $store = pdo_get("yzzc_sun_store", array("uniacid" => $_W['uniacid'], 'uid'=>$_GPC['uid']));
            if (!$store){
                $store = [];
            }
            $res['store'] = $store;
            $this->return_msg(1, $res);
        }
    }

    public function doPageHelps()
    {
        global $_W;
        $res = pdo_get("yzzc_sun_new", array("uniacid" => $_W["uniacid"]));
        $res['content'] = htmlspecialchars_decode($res['content']);
        $this->return_msg(1, $res);
    }

    public function doPageRule()
    {
        global $_W;
        $res["rule"] = pdo_getall("yzzc_sun_rule", array("uniacid" => $_W["uniacid"]));
        $res["img"] = pdo_get("yzzc_sun_banner", array("uniacid" => $_W["uniacid"]), array("rules_banner"))["rules_banner"];
        $this->return_msg(1, $res);
    }

    public function doPageWe()
    {
        global $_W;
        $res = pdo_get("yzzc_sun_we", array("uniacid" => $_W["uniacid"]));
        $this->return_msg(1, $res);
    }

    public function doPageVio()
    {
        global $_W;
        $banner = pdo_getall("wyzc_sun_violation", array("uniacid" => $_W["uniacid"], "states" => 2));
        echo json_encode($banner);
    }

    public function doPageTaocan()
    {
        global $_W;
        $res = pdo_getall("yzzc_sun_taocan", array("uniacid" => $_W["uniacid"], "status" => 1), array("id", "name", "day", "money"), '', "id desc");
        $this->return_msg(1, $res);
    }

    public function doPageActive()
    {
        global $_GPC, $_W;
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        $active = pdo_getall("yzzc_sun_active", array("uniacid" => $_W["uniacid"], "status" => 1), array(), '', "createtime desc", array($page, $length));
        foreach ($active as $key => $value) {
            if ($value["acttime"]) {
                $active[$key]["acttime"] = date("Y-m-d H:i:s", $value["acttime"]);
            }
        }
        $this->return_msg(1, $active);
    }

    public function doPageActiveInfo()
    {
        global $_GPC, $_W;
        $active = pdo_get("yzzc_sun_active", array("uniacid" => $_W["uniacid"], "aid" => $_GPC["aid"], "status" => 1));
        if ($active) {
            $this->return_msg(1, $active);
        } else {
            $this->return_msg(-1, array(), "活动不存在");
        }
    }

    public function doPageCouponList()
    {
        global $_GPC, $_W;
        $filed = array("id", 'title',"start_time", "end_time", "money", "full", "limit");
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        $res = pdo_getall("yzzc_sun_coupon", array("uniacid" => $_W["uniacid"], "status" => 1, "type" => 2, "end_time >" => time()), $filed, '', array("id desc"), array($page, $length));
        foreach ($res as $key => $value) {
            $isget = pdo_get("yzzc_sun_coupon_get", array("cid" => $value["id"], "uid" => $_GPC["uid"]));
            if ($isget) {
                $res[$key]["isget"] = 1;
            } else {
                $res[$key]["isget"] = 0;
            }
        }
        $this->return_msg(1, $res, "success");
    }

    public function doPageGetCoupon()
    {
        global $_GPC, $_W;
        if (empty($_GPC["uid"])) {
            $this->return_msg(-999, array(), "请先登录");
        }
        $uid = $_GPC["uid"];
        $sql = "select id from" . tablename("yzzc_sun_coupon_get") . "where cid=" . $_GPC["cid"] . " and uid=" . "'{$uid}'";
        $isget = pdo_fetch($sql);
        if ($isget) {
            $this->return_msg(-1, array(), "您已领过");
        }
        $info = pdo_get("yzzc_sun_coupon", array("uniacid" => $_W["uniacid"], "id" => $_GPC["cid"]));
        if ($info["end_time"] > time()) {
            if ($info["total"] == 0 || $info["total"] > $info["getnum"]) {
                $data["uid"] = $_GPC["uid"];
                $data["cid"] = $_GPC["cid"];
                $data["createtime"] = time();
                $data["uniacid"] = $_W["uniacid"];
                $data["type"] = 2;
                $res = pdo_insert("yzzc_sun_coupon_get", $data);
                pdo_update("yzzc_sun_coupon", array("getnum +=" => 1), array("id" => $_GPC["cid"]));
                if ($res) {
                    $this->return_msg(1, array(), "领取成功");
                } else {
                    $this->return_msg(-1, array(), "领取失败");
                }
            } else {
                $this->return_msg(-1, array(), "来晚了，优惠券已领完");
            }
        } else {
            $this->return_msg(-1, array(), "优惠券已过期");
        }
    }

    public function doPageMycoupon()
    {
        global $_GPC, $_W;
        if ($_GPC["type"] == 1) {
            $where = " WHERE  a.uniacid=" . $_W["uniacid"] . " and a.end_time >" . time() . "  and b.isuse = 0 ";
        } else {
            $where = " WHERE  a.uniacid=" . $_W["uniacid"] . " and a.end_time <" . time() . " and b.isuse = 0 ";
        }
        $where .= " and a.type =" . $_GPC["ctype"];
        if (empty($_GPC["uid"])) {
            $this->return_msg(-999, array(), "请先登录");
        }
        $uid = $_GPC["uid"];
        $sql = "select a.id,a.start_time,a.end_time,a.money,a.full,a.limit,b.usetime,b.createtime,b.isuse  from " . tablename("yzzc_sun_coupon") . "a " . "left join" . tablename("yzzc_sun_coupon_get") . "b on b.cid=a.id and b.uid= " . "{$uid}.{$where}";
        $mycoupon = pdo_fetchall($sql);
        $this->return_msg(1, $mycoupon);
    }

    public function doPageIntegral()
    {
        global $_GPC, $_W;
        if (empty($_GPC["uid"])) {
            $this->return_msg(-999, array(), "请先登录");
        }
        $res["user"] = pdo_get("yzzc_sun_user", array("id" => $_GPC["uid"]), array("all_integral", "now_integral"));
        $res["rentrule"] = pdo_get("yzzc_sun_allrule", array("type" => 1, "uniacid" => $_W["uniacid"]), array("content"));
        $res["rent"] = pdo_getall("yzzc_sun_coupon", array("type" => 1, "uniacid" => $_W["uniacid"], "end_time >=" => time(), "status" => 1), array("id", "score", "money", "full"));
        $res["jfrule"] = pdo_get("yzzc_sun_integralset", array("uniacid" => $_W["uniacid"]), array("rule"));
        $this->return_msg(1, $res);
    }

    public function doPageExchange()
    {
        global $_GPC, $_W;
        if (empty($_GPC["uid"])) {
            $this->return_msg(-999, array(), "请先登录");
        }
        $user = pdo_get("yzzc_sun_user", array("id" => $_GPC["uid"]), array("now_integral"));
        $uid = $_GPC["uid"];
        $sql = "select id from" . tablename("yzzc_sun_coupon_get") . "where cid=" . $_GPC["cid"] . " and uid=" . "'{$uid}'";
        $isget = pdo_fetch($sql);
        if ($isget) {
            $this->return_msg(-1, array(), "您已领过");
        }
        $info = pdo_get("yzzc_sun_coupon", array("uniacid" => $_W["uniacid"], "id" => $_GPC["cid"]));
        if ($user["now_integral"] < $info["score"]) {
            $this->return_msg(-1, array(), "积分不足，无法兑换");
        }
        if ($info["end_time"] > time()) {
            if ($info["total"] == 0 || $info["total"] > $info["getnum"]) {
                $data["uid"] = $_GPC["uid"];
                $data["cid"] = $_GPC["cid"];
                $data["createtime"] = time();
                $data["uniacid"] = $_W["uniacid"];
                $data["type"] = 1;
                $res = pdo_insert("yzzc_sun_coupon_get", $data);
                pdo_update("yzzc_sun_coupon", array("getnum +=" => 1), array("id" => $_GPC["cid"]));
                if ($res) {
                    $this->scoreAct($uid, 2, -$info["score"]);
                    $this->return_msg(1, array(), "领取成功");
                } else {
                    $this->return_msg(-1, array(), "领取失败");
                }
            } else {
                $this->return_msg(-1, array(), "来晚了，优惠券已领完");
            }
        } else {
            $this->return_msg(-1, array(), "租车券已过期");
        }
    }

    public function doPageIntegralDetails()
    {
        global $_GPC, $_W;
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        if ($_GPC["type"] == 1) {
            $where = array("uniacid" => $_W["uniacid"], "uid" => $_GPC["uid"]);
        } else {
            $where = array("uniacid" => $_W["uniacid"], "uid" => $_GPC["uid"], "type" => 2);
        }
        $res = pdo_getall("yzzc_sun_integral_log", $where, array(), '', array("id desc"), array($page, $length));
        foreach ($res as $key => $value) {
            $res[$key]["createtime"] = date("Y-m-d H:i:s", $value["createtime"]);
        }
        $this->return_msg(1, $res);
    }

    public function doPageFjshop()
    {
        global $_GPC, $_W;
        $lng = $_GPC["lng"];
        $lat = $_GPC["lat"];
        if ($lat && $lng) {
            $sql = "SELECT  id, name,city,area,address,ranges,( 6371 * acos (
            \ncos ( radians(" . $lat . ") )
            \n* cos( radians( lat ) )
                \n* cos( radians( lng ) - radians(" . $lng . ") )    \n                + sin ( radians(" . $lat . ") )    \n                * sin( radians( lat ) )    )    \n                ) AS distance FROM ims_yzzc_sun_branch  WHERE uniacid = " . $_W["uniacid"] . " and status =1 and ranges >0 HAVING distance < ranges ORDER BY distance asc";
            $data = pdo_fetchall($sql);

            foreach ($data as $key => $val) {
                $cityname = $this->getcode($val["city"]);
                $data[$key]["city_name"] = $cityname["fullname"];
                $areaname = $this->getcode($val["area"]);
                $data[$key]["area_name"] = $areaname["fullname"];
            }
            $this->return_msg(1, $data);
        } else {
            $this->return_msg(-1, array(), "请先获取地理位置");
        }
    }

    public function doPageBranch()
    {
        global $_GPC, $_W;
        if ($_GPC["id"] > 0) {
            $bran = pdo_get("yzzc_sun_branch", array("uniacid" => $_W["uniacid"], "id" => $_GPC["id"], "status" => 1));
            if ($bran) {
                $cityname = $this->getcode($bran["city"]);
                $bran["city_name"] = $cityname["fullname"];
                $areaname = $this->getcode($bran["area"]);
                $bran["area_name"] = $areaname["fullname"];
                if ($bran["pic"]) {
                    $bran["pic"] = explode(",", $bran["pic"]);
                }
                $this->return_msg(1, $bran);
            } else {
                $this->return_msg(-1, array(), "门店不存在");
            }
        } else {
            $this->return_msg(-1, array(), "门店id不存在");
        }
    }

    public function doPageAllshop()
    {
        global $_W;
        $bran = pdo_get("yzzc_sun_branch", array("uniacid" => $_W["uniacid"], "status" => 1));
        $this->return_msg(1, $bran);
    }

    public function doPageSmshop()
    {
        global $_GPC, $_W;
        $lng = $_GPC["lng"];
        $lat = $_GPC["lat"];
        if ($lat && $lng) {
            $sql = "SELECT id,name,address,ranges,city,area,( 6371 * acos (    \n                cos ( radians(" . $lat . ") )    \n                * cos( radians( lat ) )    \n                * cos( radians( lng ) - radians(" . $lng . ") )    \n                + sin ( radians(" . $lat . ") )    \n                * sin( radians( lat ) )    )    \n                ) AS distance FROM ims_yzzc_sun_branch  WHERE uniacid = " . $_W["uniacid"] . " and status =1 and ranges > ( 6371 * acos (    \n                cos ( radians(" . $lat . ") )    \n                * cos( radians( lat ) )    \n                * cos( radians( lng ) - radians(" . $lng . ") )    \n                + sin ( radians(" . $lat . ") )    \n                * sin( radians( lat ) )    )    \n                )  ORDER BY distance";
            $data = pdo_fetchall($sql);
            $this->return_msg(1, $data);
        } else {
            $this->return_msg(-1, array(), "请先获取地理位置");
        }
    }

    public function doPageCartype()
    {
        global $_W;
        $type = pdo_getall("yzzc_sun_cartype", array("uniacid" => $_W["uniacid"]));
        $this->return_msg(1, $type);
    }

    public function doPageCarList()
    {
        global $_GPC, $_W;
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        $start = ($page - 1) * $length;
        $sid = $_GPC["sid"];
        $stime = $_GPC["stime"];
        $etime = $_GPC["etime"];
        $lat = $_GPC["lat"];
        $lng = $_GPC['lng'];

        $where = 'a.is_del = 0 and a.audit_status =1 and b.status = 1 and a.status =1 and a.uniacid='.$_W["uniacid"];
        //分类
        if ($_GPC["cartype"]) {
            $where.=' and a.cartype='.$_GPC["cartype"];
        }
        //商户
        if ($_GPC["sid"]) {
            $where.=' and a.sid='.$sid;
        }
        //品牌
        if ($_GPC["brand_id"]) {
            $where.=' and a.brand_id='.$_GPC["brand_id"];
        }
        //标签
        if ($_GPC["tag_id"]) {
            $where.= " and (a.tag_id = {$_GPC["tag_id"]} or a.tag_id like '%{$_GPC["tag_id"]}%' or a.tag_id like '%,{$_GPC["tag_id"]}%' or a.tag_id like '%{$_GPC["tag_id"]},%')";
        }
        $sort = $_GPC["sort"];
        $order = '';
        if ($_GPC['order'] == 'default' || empty($_GPC['order'])){
            $order = 'a.hot asc,id desc';
        }elseif ($_GPC['order'] == 'money'){
            $order = 'a.money '.$sort;
        }elseif ($_GPC['order'] == 'distance'){
            $order = 'distance '.$sort;
        }

        $sql = "select  a.id,a.name,a.structure,a.grarbox,a.num,a.pic,a.money,a.tag_id,a.brand_id,a.cartype,b.name as branch_name,b.lng,b.lat,( 6371 * acos (cos ( radians(" . $lat . ") )* cos( radians( b.lat ) ) * cos( radians( b.lng ) - radians(" . $lng . ") )+ sin ( radians(" . $lat . ") )* sin( radians( b.lat ) ) ) ) AS distance from " . tablename("yzzc_sun_goods") . "a " . "left join" . tablename("yzzc_sun_branch") . "b on b.id=a.sid  where ".$where. " order by ".$order." limit " . $start . "," . $length;
        $res = pdo_fetchall($sql);
        //$res = pdo_getall("yzzc_sun_goods", $where, $filed, '', $orderby, array($page, $length));
        //$res1 = [];
        foreach ($res as $k => $v) {
            $cid = $v["id"];
            $carnum = $v["carnum"];
            if ($v['pic']){
                $pic = explode(',',$v['pic']);
                $res[$k]['pic'] = $pic[0];
            }
            //标签
            $tags = [];
            if ($v['tag_id']){
                $tags = pdo_fetchall('select * from '.tablename('yzzc_sun_car_tag').' where uniacid='.$_W['uniacid'].' and id in('.$v['tag_id'].')') ?? [];
            }
            $res[$k]['tags'] = $tags;

            if ($v['brand_id']){
                $brand = pdo_get('yzzc_sun_car_tag',['uniacid'=>$_W['uniacid'],'id'=>$v['brand_id']]);
            }
            $res[$k]['brand_name'] = $brand['name'] ?? '';

            if ($v['cartype']){
                $cartype = pdo_get('yzzc_sun_cartype',['uniacid'=>$_W['uniacid'],'id'=>$v['cartype']]);
            }
            $res[$k]['car_type_name'] = $cartype['name'] ?? '';

            //sku
            $sku = pdo_getall('yzzc_sun_goods_sku',['goods_id'=>$v['id'],'is_del'=>0]);
            $sku_id = 0;
            foreach ($sku as $key => $value){
                if ($this->CheckSku($value['id'],$cid,$stime,$etime) === false){
                    continue;
                }else{
                    $sku_id = $value['id'];
                    $carnum = $value['carnum'];
                    $colour = $value['colour'];
                    $displacement = $value['displacement'];
                    break;
                }
            }
            if ($sku_id == 0){
                unset($res[$k]);
            }else{
                $res[$k]['sku_id'] = $sku_id;
                $res[$k]['carnum'] = $carnum ?? '';
                $res[$k]['colour'] = $colour ?? '';
                $res[$k]['displacement'] = $displacement ?? '';
            }

//            $allordertime = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and sku_id = {$sku_id} and goods_id={$cid}");
//            if ($allordertime) {
//                foreach ($allordertime as $key => $value) {
//                    $start_time = $value["start_time"];
//                    $end_time = $value["end_time"];
//                    if ($stime < $start_time && $etime > $end_time && $start_time < $etime && $stime < $end_time) {
//                        if ($res[$k] != null) {
//                            array_push($res1, $res[$k]);
//                            unset($res[$k]);
//                        }
//                    } else {
//                        if ($stime < $start_time && $end_time > $etime && $start_time < $etime && $stime < $end_time) {
//                            if ($res[$k] != null) {
//                                array_push($res1, $res[$k]);
//                                unset($res[$k]);
//                            }
//                        } else {
//                            if ($start_time < $stime && $etime > $end_time && $start_time < $etime && $stime < $end_time) {
//                                if ($res[$k] != null) {
//                                    array_push($res1, $res[$k]);
//                                    unset($res[$k]);
//                                }
//                            } else {
//                                if ($start_time < $stime && $end_time > $etime && $start_time < $etime && $stime < $end_time) {
//                                    if ($res[$k] != null) {
//                                        array_push($res1, $res[$k]);
//                                        unset($res[$k]);
//                                    }
//                                } else {
//
//                                }
//                            }
//                        }
//                    }
//                }
//            }
        }
        //$info = array("res" => $res);
        $this->return_msg(1, $res, "success");
    }

    /**
     * @return void
     * 预订下单车辆列表
     */
    public function doPageGetCarList()
    {
        global $_GPC, $_W;

        $where = 'is_del = 0 and audit_status = 1 and status = 1 and uniacid='.$_W["uniacid"];

        $sql = "select id from " . tablename("yzzc_sun_goods") . " where ".$where;

        $res = pdo_fetchall($sql);

        $sku_list = [];
        if ($res){
            $res = array_column($res,'id');
            $sku_list = pdo_getall('yzzc_sun_goods_sku',['goods_id in'=>$res],['id','name','carnum']);
        }

        $this->return_msg(1, $sku_list, "success");
    }

    /**
     * @return void
     *
     */
    public function doPageGetBranchList()
    {
        global $_GPC, $_W;

        $where = 'status = 1 and uniacid='.$_W["uniacid"];

        $sql = "select id,name from " . tablename("yzzc_sun_branch") . " where ".$where;

        $res = pdo_fetchall($sql);


        $this->return_msg(1, $res, "success");
    }

    /**
     * @return void
     *
     */
    public function doPageGetShuttleList()
    {
        global $_GPC, $_W;

        $where = 'uniacid='.$_W["uniacid"];

        $sql = "select id,name from " . tablename("yzzc_sun_shuttle") . " where ".$where;

        $res = pdo_fetchall($sql);


        $this->return_msg(1, $res, "success");
    }
    public function doPageGetarea()
    {
        global $_GPC, $_W;
        $code = $_GPC["code"];
        $where = " WHERE  uniacid=" . $_W["uniacid"] . " and city =" . $code . " and status= 1 ";
        $sql = "SELECT  distinct  area FROM ims_yzzc_sun_branch " . $where;
        $area = pdo_fetchall($sql);
        foreach ($area as $key => $value) {
            $areainfo = pdo_get("yzzc_sun_city", array("code" => $value["area"]), array("fullname"));
            $area[$key]["fullname"] = $areainfo["fullname"];
        }
        $this->return_msg(1, $area, "success");
    }

    public function doPageAreashop()
    {
        global $_GPC, $_W;
        $where = array("uniacid" => $_W["uniacid"], "area" => $_GPC["code"], "status" => 1);
        $filed = array("id", "name", "address");
        $res = pdo_getall("yzzc_sun_branch", $where, $filed, "id desc");
        $this->return_msg(1, $res, "success");
    }

    /**
     * @return void
     * 门店取还取车
     */
    public function doPageCityshop()
    {
        global $_GPC, $_W;
        $lat = $_GPC['lat'] ?? '30.5702';
        $lng = $_GPC['lng'] ?? '104.06476';
        if (!$lat || !$lng){
            $this->return_msg(-1, '','请先获取经纬度');
        }
        $sql = "SELECT  id, name,address,ranges,city,area,( 6371 * acos (
            \ncos ( radians(" . $lat . ") )
            \n* cos( radians( lat ) )
                \n* cos( radians( lng ) - radians(" . $lng . ") )    \n                + sin ( radians(" . $lat . ") )    \n                * sin( radians( lat ) )    )    \n                ) AS distance FROM ims_yzzc_sun_branch  WHERE uniacid = " . $_W["uniacid"] . " and status = 1 and city = ".$_GPC["code"]." ORDER BY distance asc";
        $data = pdo_fetchall($sql);

        foreach ($data as $key => $val) {
            $cityname = $this->getcode($val["city"]);
            $data[$key]["city_name"] = $cityname["fullname"];
            $areaname = $this->getcode($val["area"]);
            $data[$key]["area_name"] = $areaname["fullname"];
        }

        $this->return_msg(1, $data);
    }

    public function doPageAllcity()
    {
        global $_W;
        $where = " WHERE  uniacid=" . $_W["uniacid"] . " and status= 1 ";
        $sql = "SELECT  distinct  city FROM ims_yzzc_sun_branch " . $where;
        $area = pdo_fetchall($sql);
        foreach ($area as $key => $value) {
            $areainfo = pdo_get("yzzc_sun_city", array("code" => $value["city"]), array("fullname"));
            $area[$key]["fullname"] = $areainfo["fullname"];
        }
        $this->return_msg(1, $area, "success");
    }

    function mylevel($score)
    {
        global $_W;
        $res = pdo_getall("yzzc_sun_level", array("uniacid" => $_W["uniacid"]), array(), '', array("level_score asc"));
        $arr = array();
        foreach ($res as $val) {
            array_push($arr, $val["level_score"]);
        }
        $level = 0;
        foreach ($arr as $key => $value) {
            if ($score > $value) {
                $level++;
            }
        }
        $myres = pdo_getall("yzzc_sun_level", array("uniacid" => $_W["uniacid"]), array(), '', array("level_score asc"));
        if ($level > 0) {
            $mylevel = $myres[$level - 1];
        } else {
            $mylevel = $myres[$level];
        }
        return $mylevel;
    }

    function mytq($score)
    {
        global $_W;
        $res = pdo_getall("yzzc_sun_level", array("uniacid" => $_W["uniacid"]), array(), '', array("level_score asc"));
        $arr = array();
        foreach ($res as $val) {
            if ($score > $val["level_score"]) {
                array_push($arr, $val);
            }
        }
        if (empty($arr)) {
            $arr[0] = $res[0];
        }
        return $arr;
    }

    public function doPageMember()
    {
        global $_GPC, $_W;
        $user = pdo_get("yzzc_sun_user", array("id" => $_GPC["uid"]), array("all_integral", "user_name", "headimg"));
        $res = pdo_getall("yzzc_sun_level", array("uniacid" => $_W["uniacid"]), array(), "level_score asc");
        $score = array();
        foreach ($res as $val) {
            array_push($score, $val["level_score"]);
        }
        $now = $user["all_integral"];
        $level = 0;
        foreach ($score as $key => $value) {
            if ($now > $value) {
                $level++;
            }
        }
        if ($level == count($res)) {
            $data["cha"] = -1;
        } else {
            $myres = pdo_getall("yzzc_sun_level", array("uniacid" => $_W["uniacid"]), array(), "level_score asc", $level, 2);
            $cha = $myres[1]["level_score"] - $user["all_integral"];
            $data["cha"] = $cha;
        }
        $data["list"] = $res;
        $data["mylevel"] = $this->mylevel($user["all_integral"]);
        $rule = pdo_get("yzzc_sun_allrule", array("uniacid" => $_W["uniacid"], "type" => 2), array("content"));
        $data["rule"] = $rule["content"];
        $data["userinfo"] = $user;
        $this->return_msg(1, $data, "success");
    }

    function getTimeWeek($time, $i = 0)
    {
        $weekarray = array("日", "一", "二", "三", "四", "五", "六");
        $oneD = 24 * 60 * 60;
        return "周" . $weekarray[date("w", $time + $oneD * $i)];
    }

    function carInfo($cid)
    {
        $info = pdo_get("yzzc_sun_goods", array("id" => $cid, "status" => 1));
        return $info;
    }

    function getcode($code)
    {
        $cityinfo = pdo_get("yzzc_sun_city", array("code" => $code));
        return $cityinfo;
    }

    public function doPageShopname()
    {
        global $_GPC, $_W;
        $sid = $_GPC["sid"];
        $info = pdo_get("yzzc_sun_branch", array("id" => $sid), array("id", "name", "province", "city", "area"));
        if ($info) {
            $info["province_name"] = $this->getcode($info["province"])["fullname"];
            $info["city_name"] = $this->getcode($info["city"])["fullname"];
            $info["area_name"] = $this->getcode($info["area"])["fullname"];
        }
        $this->return_msg(1, $info, "success");
    }

    public function doPageYdcar()
    {
        global $_GPC, $_W;
        $info = $this->carInfo($_GPC["cid"]);
        $ordertime = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where carnum = '" . $info["carnum"] . "' and uniacid = " . $_W["uniacid"] . " and end_time >" . time() . " order by start_time desc");
        foreach ($ordertime as $key => $value) {
            $ordertime[$key]["start_time"] = date("Y-m-d H:i:s", $value["start_time"]);
            $ordertime[$key]["end_time"] = date("Y-m-d H:i:s", $value["end_time"]);
        }
        $info["ordertime"] = $ordertime;
        $info["shopinfo"] = pdo_get("yzzc_sun_branch", array("id" => $info["sid"]), array("id", "name", "province", "city", "area"));
        $info["shopinfo"]["province_name"] = $this->getcode($info["shopinfo"]["province"])["fullname"];
        $info["shopinfo"]["city_name"] = $this->getcode($info["shopinfo"]["city"])["fullname"];
        $info["shopinfo"]["area_name"] = $this->getcode($info["shopinfo"]["area"])["fullname"];
        $this->return_msg(1, $info, "success");
    }

    public function doPagexzdetail()
    {
        global $_W, $_GPC;
        $oid = $_GPC["oid"];
        $day = $_GPC["day"] ? $_GPC["day"] : 1;
        $data = pdo_get("yzzc_sun_order", array("uniacid" => $_W["uniacid"], "id" => $oid, "status" => 3));
        $data["carinfo"] = pdo_get("yzzc_sun_goods", array("uniacid" => $_W["uniacid"], "id" => $data["cid"]));
        $allday = [];
        $i = 0;
        while ($i < $day) {
            array_push($allday, date("Y-m-d", $data["end_time"] + $i * 24 * 60 * 60));
            $i++;
        }
        $money = 0;
        $spec = [];
        if ($data["carinfo"]["subscribe_duration"]) {
            $data["carinfo"]["spec"] = pdo_fetchall("select * from " . tablename("yzzc_sun_specprice") . " where uniacid =" . $_W["uniacid"] . " and gid = " . $data["cid"] . " order by spec asc");
            foreach ($data["carinfo"]["spec"] as $key => $value) {
                foreach ($allday as $k => $v) {
                    if ($value["spec"] == $v) {
                        $money += $value["price"];
                        array_push($spec, $value);
                        unset($allday[$k]);
                    }
                }
            }
        }
        $user = pdo_get("yzzc_sun_user", array("id" => $data["uid"]), array("all_integral", "now_integral"));
        $levelinfo = $this->mylevel($user["all_integral"]);
        if ($levelinfo["level_privileges"] == 2) {
            $data["is_service_fee"] = 0;
            $data["carinfo"]["service_fee"] = 0;
        } else {
            $data["is_service_fee"] = 1;
        }
        $data["time"]["day"] = count($allday);
        $data["carinfo"]["specprice"] = $money;
        $data["carinfo"]["spec"] = $spec;
        $data["carinfo"]["specday"] = count($spec);
        $orderset = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("know", "long_prepay", "short_prepay", "service_desc", "zx_service_desc", "rule", "zchetong"));
        $orderset['service_desc'] = htmlspecialchars_decode($orderset['service_desc']);
        $orderset['zx_service_desc'] = htmlspecialchars_decode($orderset['zx_service_desc']);
        $orderset['know'] = htmlspecialchars_decode($orderset['know']);
        $orderset['rule'] = htmlspecialchars_decode($orderset['rule']);
        $data["orderset"] = $orderset;
        $data["shopinfo"] = pdo_get("yzzc_sun_branch", array("id" => $data["carinfo"]["sid"]), array("id", "name", "province", "city", "area"));
        $data["shopinfo"]["province_name"] = $this->getcode($data["shopinfo"]["province"])["fullname"];
        $data["shopinfo"]["city_name"] = $this->getcode($data["shopinfo"]["city"])["fullname"];
        $data["shopinfo"]["area_name"] = $this->getcode($data["shopinfo"]["area"])["fullname"];
        $integralset = pdo_get("yzzc_sun_integralset", array("uniacid" => $_W["uniacid"]), array("use_score", "use_money"));
        $data["integral_set"] = $integralset;
        if ($integralset["use_score"] > 0) {
            $ystotal = $data["carinfo"]["money"] * $data["time"]["day"] + $data["carinfo"]["service_fee"] * $data["time"]["day"] + $money;
            $ystotal = intval($ystotal);
            $allscore = $ystotal * intval($data["integral_set"]["use_score"]) / intval($integralset["use_money"]);
            $data["user"] = pdo_get("yzzc_sun_user", array("id" => $data["uid"]), array("now_integral"));
            if ($allscore > $data["user"]["now_integral"]) {
                $data["kdmoney"] = $data["user"]["now_integral"] / $integralset["use_score"] * $integralset["use_money"];
                $data["kdscore"] = $data["user"]["now_integral"];
            } else {
                $data["kdscore"] = $allscore;
                $data["kdmoney"] = $allscore / $integralset["use_score"] * $integralset["use_money"];
            }
            $data["kdmoney"] = sprintf("%.2f", $data["kdmoney"]);
            $data["kycoupontotal"] = $ystotal - $data["kdmoney"] - 0.01;
        }
        $this->return_msg(1, $data, "success");
    }

    public function doPagexzOrder()
    {
        global $_GPC, $_W;
        $oid = $_GPC["oid"];
        $order = pdo_get("yzzc_sun_order", array("uniacid" => $_W["uniacid"], "id" => $oid, "status" => 3));
        if (!$order) {
            $this->return_msg(-1, array(), "续租失败！");
        }
        if ($order["iszx"] == 1) {
            $this->return_msg(-1, array(), "该订单已续租，无法重复续租！");
        }
        $xzorder = pdo_get("yzzc_sun_xzorder", array("uniacid" => $_W["uniacid"], "ordernum" => $order["ordernum"]));
        if ($xzorder["ispay"] == 1) {
            $this->return_msg(-1, array(), "该订单已续租，无法重复续租！");
        }
        $data["uniacid"] = $_W["uniacid"];
        $data["createtime"] = time();
        $start_time = $order["end_time"];
        $end_time = $_GPC["end_time"];
        $couponid = $_GPC["couponid"];
        $carinfo = pdo_get("yzzc_sun_goods", array("id" => $order["cid"], "status !=" => 3, "is_del" => 0));
        if ($carinfo) {
            $data["start_time"] = $start_time;
            $data["end_time"] = $end_time;
            $day = $_GPC["day"];
            $data["day"] = $day;
            $data["money"] = $order["money"];
            $user = pdo_get("yzzc_sun_user", array("id" => $order["uid"]), array("all_integral", "now_integral"));
            $levelinfo = $this->mylevel($user["all_integral"]);
            if ($levelinfo["level_privileges"] == 2) {
                $data["service_fee"] = 0;
            } else {
                $data["service_fee"] = $carinfo["service_fee"];
            }
            if ($levelinfo["level_privileges"] == 3) {
                $data["end_time"] = $end_time + $levelinfo["delay"] * 60 * 60;
            }
            if ($carinfo["zx_service_fee"] > 0) {
                $data["open_zx_service"] = $_GPC["open_zx_service"];
                if ($_GPC["open_zx_service"] == 1) {
                    $data["zx_service_fee"] = $carinfo["zx_service_fee"];
                }
            }
            $data["integral_money"] = 0;
            if ($_GPC["open_integral"] == 1) {
                if ($user["now_integral"] >= $_GPC["integral"]) {
                    $data["integral_money"] = $_GPC["integral_money"];
                    $data["integral"] = $_GPC["integral"];
                    if ($data["integral"] > 0) {
                        $this->scoreAct($order["uid"], 4, -$data["integral"]);
                    }
                }
            }
            $data["coupon"] = 0;
            if ($couponid > 0) {
                $coupon = pdo_get("yzzc_sun_coupon", array("id" => $couponid));
                $data["coupon_money"] = $coupon["money"];
                $data["coupon"] = $couponid;
                pdo_update("yzzc_sun_coupon_get", array("isuse" => 1, "usetime" => time()), array("cid" => $couponid, "uid" => $order["uid"]));
            }
            $data["total_money"] = $_GPC["total_money"];
            $data["ordernum"] = $order["ordernum"];
            pdo_insert("yzzc_sun_xzorder", $data);
            $oid = pdo_insertid();
            include_once IA_ROOT . "/addons/" . $_W["current_module"]["name"] . "/inc/func/distribution.php";
            $user = pdo_get("yzzc_sun_user", array("id" => $order["uid"]));
            $distribution = new Distribution();
            $distribution->order_id = $order["id"];
            $distribution->money = $data["total_money"];
            $distribution->userid = $user["openid"];
            $distribution->ordertype = 3;
            $distribution->computecommission();
            if ($oid) {
                $this->return_msg(1, $oid, "success");
            }
        } else {
            $this->return_msg(-1, array(), "当前车辆已下架，无法续租！");
        }
    }

    public function doPageCheckOrd()
    {
        global $_GPC, $_W;
        $cid = $_GPC["goods_id"] ?? $_GPC['cid'];
        $sku_id = $_GPC["sku_id"] ?? $_GPC['sku_id'];
        $uid = $_GPC["uid"];
        $user_drive = pdo_get("yzzc_sun_user_drive", array("uniacid" => $_W["uniacid"], "is_mr" => 1, "uid" => $uid),['id','name','phone','sfcode']);
        $data["user_drive"] = $user_drive;
        $day = $_GPC["day"] - 0;
        $allday = [];
        $i = 0;
        while ($i < $day) {
            array_push($allday, date("Y-m-d", trim($_GPC["start_time"]) + $i * 24 * 60 * 60));
            $i++;
        }

        $money = 0;
        $spec = [];
        $data["carinfo"] = pdo_get("yzzc_sun_goods", array("id" => $cid, "status" => 1));

        $sku = pdo_get('yzzc_sun_goods_sku',['id'=>$sku_id,'is_del'=>0],['carnum','colour','displacement','id','cartype']);
        $data["carinfo"]['carnum'] = $sku['carnum'];
        $data["carinfo"]['colour'] = $sku['colour'];
        $data["carinfo"]['displacement'] = $sku['displacement'];
        $data["carinfo"]['sku_id'] = $sku['id'];

        if ($sku['cartype']){
            $cartype = pdo_get('yzzc_sun_cartype',['uniacid'=>$_W['uniacid'],'id'=>$sku['cartype']]);
            $data["carinfo"]['car_type_name'] = $cartype['name'] ?? '';
        }
        if ($data["carinfo"]["subscribe_duration"]) {
            $data["carinfo"]["spec"] = pdo_fetchall("select * from " . tablename("yzzc_sun_specprice") . " where uniacid =" . $_W["uniacid"] . " and gid = " . $cid . " order by spec asc");
            foreach ($data["carinfo"]["spec"] as $key => $value) {
                foreach ($allday as $k => $v) {
                    if ($value["spec"] == $v) {
                        $money += $value["price"];
                        array_push($spec, $value);
                        unset($allday[$k]);
                    }
                }
            }
        }
//        订单设置
        $orderset = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("know", "long_prepay", "short_prepay", "service_desc", "zx_service_desc", "rule", "zchetong",'getcar_desc', "depositway", "deposit",'hour_type','istui','tuimoney'));
        $orderset['service_desc'] = htmlspecialchars_decode($orderset['service_desc']);
        $orderset['zx_service_desc'] = htmlspecialchars_decode($orderset['zx_service_desc']);
        $orderset['rule'] = htmlspecialchars_decode($orderset['rule']);
        $orderset['know'] = htmlspecialchars_decode($orderset['know']);
        $data["orderset"] = $orderset;

        $max_hour = $_GPC["end_time"] -  $_GPC["start_time"];
        $max_hour = round(floor($max_hour)%86400/3600,2);
        $beyond_hour_price = 0;
        if ($orderset['hour_type'] == 1){
            //按小时算
            $beyond_hour_price = round($data["carinfo"]["money"] / 24) * $max_hour;
        }elseif ($orderset['hour_type'] == 2){
            $max_hour = round(floor($max_hour)%86400/3600,2);
            if ($max_hour >= 4) {
                $beyond_hour_price = 0;
                $data["time"]["day"]+=1;
            }else{
                $beyond_hour_price = $data["carinfo"]["money"] / 2;
            }
        }
        $data["time"]["day"] = count($allday);
        $data["carinfo"]["specprice"] = $money; //节假日费用
        $data["carinfo"]["spec"] = $spec;
        $data["carinfo"]["specday"] = count($spec); //节假日天数
        $data["shopinfo"] = pdo_get("yzzc_sun_branch", array("id" => $data["carinfo"]["sid"]), array("id", "name", "province", "city", "area",'address','shop_tel','ranges','lat','lng'));
        $data["shopinfo"]["province_name"] = $this->getcode($data["shopinfo"]["province"])["fullname"];
        $data["shopinfo"]["city_name"] = $this->getcode($data["shopinfo"]["city"])["fullname"];
        $data["shopinfo"]["area_name"] = $this->getcode($data["shopinfo"]["area"])["fullname"];

        //押金
        $deposit = $orderset['deposit'];
        if ($data["carinfo"]['depositway'] == 1){
            //单独使用押金
            $deposit = $data["carinfo"]['deposit'];
        }

        $data['fee'] = $data["carinfo"]["fee"]; //手续费
        $data['service_fee'] = $data["carinfo"]["service_fee"] * $data["time"]["day"];//基础服务费
        $data['festival'] = $money;//节假日费用
        $data['deposit'] = $deposit;//押金
        $data['money'] = $data["carinfo"]["money"] * $data["time"]["day"];//租金
        $data['money'] = sprintf("%.2f", $data['money']);
        if (isset($_GPC['coupon_id']) && $_GPC['coupon_id']){
            //计算订单优惠
            $coupon_id = $_GPC['coupon_id'];
            $where = " WHERE  a.uniacid=" . $_W["uniacid"] . " and a.end_time >" . time() . " and a.start_time < " . time() . " and b.isuse = 0 and a.money < " . $data['money'].' and a.id='.$coupon_id;
            $sql = "select a.id,a.title,a.money  from " . tablename("yzzc_sun_coupon") . "a " . "left join" . tablename("yzzc_sun_coupon_get") . "b on b.cid=a.id and b.uid= " . "{$uid}.{$where}";
            $ky_coupon = pdo_fetch($sql);
            if (!$ky_coupon){
                $this->return_msg(-1,[],'优惠劵使用错误');
            }
            $data['money'] = $data['money'] - $ky_coupon['money'];
            if ($data['money'] <= 0){
                $this->return_msg(-1,[],'支付金额错误');
            }
            $data['coupon'] = $ky_coupon;
            $data['coupon_money'] = $ky_coupon['money'];
        }
        $data['total_amount'] = $data['fee'] + $data['service_fee'] + $data['festival'] + $data['money'] + $beyond_hour_price;//总金额
        $data['total_amount'] =  sprintf("%.2f", $data['total_amount']);
//        $user = pdo_get("yzzc_sun_user", array("id" => $uid), array("all_integral", "now_integral"));
//        $levelinfo = $this->mylevel($user["all_integral"]);
//        if ($levelinfo["level_privileges"] == 2) {
//            $data["is_service_fee"] = 0;
//            $data["carinfo"]["service_fee"] = 0;
//        } else {
//            $data["is_service_fee"] = 1;
//        }
//        $integralset = pdo_get("yzzc_sun_integralset", array("uniacid" => $_W["uniacid"]), array("use_score", "use_money"));
//        $data["integral_set"] = $integralset;
//        if ($integralset["use_score"] > 0) {
//            $ystotal = $data["carinfo"]["money"] * $data["time"]["day"] + $data["carinfo"]["service_fee"] * $data["time"]["day"] + $data["carinfo"]["fee"] + $money;
//            if ($data["carinfo"]['depositway'] == 1){
//                //单独使用押金
//                $ystotal+= $data["carinfo"]['deposit'];
//            }
//            $ystotal = intval($ystotal);
//            $allscore = $ystotal * intval($data["integral_set"]["use_score"]) / intval($integralset["use_money"]);
//            $data["user"] = pdo_get("yzzc_sun_user", array("id" => $uid), array("now_integral"));
//            if ($allscore > $data["user"]["now_integral"]) {
//                $data["kdmoney"] = $data["user"]["now_integral"] / $integralset["use_score"] * $integralset["use_money"];
//                $data["kdscore"] = $data["user"]["now_integral"];
//            } else {
//                $data["kdscore"] = $allscore;
//                $data["kdmoney"] = $allscore / $integralset["use_score"] * $integralset["use_money"];
//            }
//            $data["kdmoney"] = sprintf("%.2f", $data["kdmoney"]);
//            $data["kycoupontotal"] = $ystotal - $data["kdmoney"] - 0.01;
//        }

        $this->return_msg(1, $data, "success");
    }



    /**
     * @return void
     * 查询订单可用优惠劵
     */
    public function doPageKycoupon()
    {
        global $_GPC, $_W;
        $uid = $_GPC["uid"];
        $where = " WHERE  a.uniacid=" . $_W["uniacid"] . " and a.end_time >" . time() . " and a.start_time < " . time() . " and b.isuse = 0 and a.money < " . $_GPC["full"];
        $sql = "select a.id,a.title,a.start_time,a.end_time,a.money,a.full,a.limit,b.usetime,b.createtime,b.isuse,a.type  from " . tablename("yzzc_sun_coupon") . "a " . "left join" . tablename("yzzc_sun_coupon_get") . "b on b.cid=a.id and b.uid= " . "{$uid}.{$where}";
        $kycoupon = pdo_fetchall($sql);
        $this->return_msg(1, $kycoupon, "success");
    }

    /**
     * @return void
     * 订单设置
     */
    public function doPageOrderSet(){
        global $_GPC, $_W;
        $order = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]));
        $order['rule'] = htmlspecialchars_decode($order['rule']);
        $order['service_desc'] = htmlspecialchars_decode($order['service_desc']);
        $order['zx_service_desc'] = htmlspecialchars_decode($order['zx_service_desc']);
        $order['zchetong'] = htmlspecialchars_decode($order['zchetong']);
        $order['invoice'] = $order['invoice'] ? explode(',',$order['invoice']) : [];
        $order['invoice_content'] = $order['invoice_content'] ? explode(',',$order['invoice_content']) : [];
        $this->return_msg(1,$order);

    }

    /**
     * @return void
     * 查询车辆是否被租用
     */
    public function doPageIsorder()
    {
        global $_GPC, $_W;
        $cid = $_GPC["goods_id"];
        $sku_id = $_GPC["sku_id"];
        $uid = $_GPC["uid"];
        $stime = $_GPC["stime"];
        $etime = $_GPC["etime"];

        $user_drive = pdo_get('yzzc_sun_user_drive',['uniacid'=>$_W['uniacid'],'uid'=>$uid]);
        if (!$user_drive){
            $this->return_msg(-2, array(), "请先完成实名认证");
        }

        $sku = pdo_get('yzzc_sun_goods_sku',['uniacid'=>$_W['uniacid'],'goods_id'=>$cid,'id'=>$sku_id]);
        if (!$sku){
            $this->return_msg(-2, array(), "车型不存在");
        }

        $order = pdo_fetch("select id from " . tablename("yzzc_sun_order") . " where uniacid = " . $_W["uniacid"] . " and cid = '{$cid}' and (status = 2 or status = 3) and sku_id = '{$sku_id}'");

        if (!$order) {
            $allorder = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and goods_id = {$cid} and sku_id = {$sku_id}");
            foreach ($allorder as $key => $value) {
                $start_time = $value["start_time"];
                $end_time = $value["end_time"];
                $starttime = date("Y-m-d H:i:s", $start_time);
                $endtime = date("Y-m-d H:i:s", $end_time);
                if ($stime < $start_time && $etime > $end_time && $start_time < $etime && $stime < $end_time) {
                    $this->return_msg(-2, array(), "您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                } else {
                    if ($stime < $start_time && $end_time > $etime && $start_time < $etime && $stime < $end_time) {
                        $this->return_msg(-2, array(), "您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                    } else {
                        if ($start_time < $stime && $etime > $end_time && $start_time < $etime && $stime < $end_time) {
                            $this->return_msg(-2, array(), "您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                        } else {
                            if ($start_time < $stime && $end_time > $etime && $start_time < $etime && $stime < $end_time) {
                                $this->return_msg(-2, array(), "您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                            } else {
                            }
                        }
                    }
                }
            }
            $this->return_msg(1, array(), "首次下单");
        }
        else {
            $allorder = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and goods_id = {$cid} and sku_id = {$sku_id}");
            foreach ($allorder as $key => $value) {
                $start_time = $value["start_time"];
                $end_time = $value["end_time"];
                $starttime = date("Y-m-d H:i:s", $start_time);
                $endtime = date("Y-m-d H:i:s", $end_time);
                if ($stime < $start_time && $etime > $end_time && $start_time < $etime && $stime < $end_time) {
                    $this->return_msg(-2, array(), "您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                } else {
                    if ($stime < $start_time && $end_time > $etime && $start_time < $etime && $stime < $end_time) {
                        $this->return_msg(-2, array(), "您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                    } else {
                        if ($start_time < $stime && $etime > $end_time && $start_time < $etime && $stime < $end_time) {
                            $this->return_msg(-2, array(), "您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                        } else {
                            if ($start_time < $stime && $end_time > $etime && $start_time < $etime && $stime < $end_time) {
                                $this->return_msg(-2, array(), "您选择的时间车辆已被出租,时间为：" . $starttime . "--" . $endtime);
                            } else {
                            }
                        }
                    }
                }
            }
            $this->return_msg(1, array(), "下单");
        }
    }

    /**
     * @param $sku_id
     * @param $goods_id
     * @param $start_time
     * @param $end_time
     * @return bool
     * 检测库存
     */
    function CheckSku($sku_id,$goods_id,$start_time,$end_time)
    {
        global $_W;
        $stime = $start_time;
        $etime = $end_time;

        $order = pdo_fetch("select id from " . tablename("yzzc_sun_order") . " where uniacid = " . $_W["uniacid"] . " and cid = '{$goods_id}' and (status = 2 or status = 3) and sku_id = '{$sku_id}'");

        $result = false;
        if (!$order) {
            $allorder = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and sku_id = '{$sku_id}' and goods_id = '{$goods_id}'");
            if (!$allorder){
                return true;
            }
            foreach ($allorder as $key => $value) {
                $start_time = $value["start_time"];
                $end_time = $value["end_time"];
                if ($stime <= $start_time && $etime >= $end_time && $start_time <= $etime && $stime <= $end_time) {
                    continue;
                } else {
                    if ($stime <= $start_time && $end_time >= $etime && $start_time <= $etime && $stime <= $end_time) {
                        continue;
                    } else {
                        if ($start_time <= $stime && $etime >= $end_time && $start_time <= $etime && $stime <= $end_time) {
                            continue;
                        } else {
                            if ($start_time <= $stime && $end_time >= $etime && $start_time <= $etime && $stime <= $end_time) {
                                continue;
                            } else {
                                $result = true;
                                break;
                            }
                        }
                    }
                }
            }
            return $result;
            //$this->return_msg(1, array(), "首次下单");
        } else {
            $allorder = pdo_fetchall("select * from " . tablename("yzzc_sun_ordertime") . " where uniacid = " . $_W["uniacid"] . " and goods_id = {$goods_id} and sku_id = {$sku_id}");
            if (!$allorder){
                return true;
            }
            foreach ($allorder as $key => $value) {
                $start_time = $value["start_time"];
                $end_time = $value["end_time"];
                if ($stime <= $start_time && $etime >= $end_time && $start_time <= $etime && $stime <= $end_time) {
                    continue;
                } else {
                    if ($stime <= $start_time && $end_time >= $etime && $start_time <= $etime && $stime <= $end_time) {
                        continue;
                    } else {
                        if ($start_time <= $stime && $etime >= $end_time && $start_time <= $etime && $stime <= $end_time) {
                            continue;
                        } else {
                            if ($start_time <= $stime && $end_time >= $etime && $start_time <= $etime && $stime <= $end_time) {
                                continue;
                            } else {
                                $result = true;
                                break;
                            }
                        }
                    }
                }
            }
            return $result;
        }
    }
    public function doPageOrderInfo()
    {
        global $_GPC, $_W;
        $order = pdo_get("yzzc_sun_order", array("id" => $_GPC["oid"]));
        $order["carinfo"] = $this->carInfo($order["cid"]);
        $info = pdo_get("yzzc_sun_branch", array("id" => $order["start_shop"]), array("id", "name", "province", "city", "area"));
        if ($info) {
            $info["province_name"] = $this->getcode($info["province"])["fullname"];
            $info["city_name"] = $this->getcode($info["city"])["fullname"];
            $info["area_name"] = $this->getcode($info["area"])["fullname"];
        }
        $order["shop"] = $info;
        $order["qcrule"] = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("rule"))["rule"];
        $order["qcrule"] = htmlspecialchars_decode($order["qcrule"]);
        if ($order) {
            $this->return_msg(1, $order, "success");
        } else {
            $this->return_msg(-1, array(), "订单不存在");
        }
    }

    /**
     * @return void
     * 上传验车图
     */
    public function doPageorderpj()
    {
        global $_GPC, $_W;
        $oid = $_GPC["oid"];
        $order = pdo_get("yzzc_sun_order", array("uniacid" => $_W["uniacid"], "id" => $oid));
        if ($order["status"] == 3 || $order["status"] == 2) {
            if ($order["ispl"] == 0) {
                $data["content"] = $_GPC["content"];
                $data["img"] = $_GPC["img"];
                $data["oid"] = $_GPC["oid"];
                $data["time"] = time();
                $data["uniacid"] = $_W["uniacid"];
                $data["carnum"] = $order["carnum"];
                $res = pdo_insert("yzzc_sun_orderpinglun", $data);
                if ($res) {
                    $result = pdo_update("yzzc_sun_order", array("ispl" => 1), array("uniacid" => $_W["uniacid"], "id" => $oid));
                    $this->return_msg(1, array(), "操作成功");
                } else {
                    $this->return_msg(-1, array(), "操作失败");
                }
            } else {
                $this->return_msg(-1, array(), "当前订单已上传验车资料");
            }
        } else {
            $this->return_msg(-1, array(), "当前订单无法评价！");
        }
    }

    /**
     * @return void
     * 订单列表
     */
    public function doPageOrderList()
    {
        global $_GPC, $_W;
        $status = $_GPC["status"];
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;

        $where = ["uniacid" => $_W["uniacid"], "uid" => $_GPC["uid"], "display" => 1];
        if ($status == 3){
            $where['status in'] = '2,3';
        }else{
            if ($status != ''){
                $where['status'] = $status;
            }
        }

        //优惠劵订单
        if (isset($_GPC['coupon_id']) && $_GPC['coupon_id'] == 1){
            $where['coupon >'] = 0;
        }

        //发票
        if (isset($_GPC['is_invoice'])){
            $where['is_invoice'] = $_GPC['is_invoice'];
        }
        $res = pdo_getall("yzzc_sun_order",$where, array('id','cid','sku_id','carnum','gettype','start_time','end_time','day','ordernum','ispay','total_money','status','start_shop','end_shop','user_address','user_lat','user_lng','is_invoice','invoice_type'), '', array("status asc", "createtime desc"), array($page, $length));
        $set = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("istui", "tuimoney", "open_xz", "xztime"));
        $day = $set["istui"] * 24 * 60 * 60;
        $hour = $set["xztime"] * 60 * 60;
        $time = time();
        foreach ($res as $key => $val) {
            $car_info = pdo_get("yzzc_sun_goods_sku", array("id" => $val["sku_id"]),['id','sid','name','structure','grarbox','pic','cartype','displacement','colour','carnum']);
            if ($car_info['cartype']){
                $cartype = pdo_get('yzzc_sun_cartype',['uniacid'=>$_W['uniacid'],'id'=>$car_info['cartype']]);
                $car_info['car_type_name'] = $cartype['name'] ?? '';
            }
            $res[$key]["carinfo"] = $car_info;

            if ($res) {
                //门店自取
                $info = pdo_get("yzzc_sun_branch", array("id" => $val["start_shop"]), array("id", "name", "province", "city", "area",'address','lat','lng','shop_tel'));
                $info["province_name"] = $this->getcode($info["province"])["fullname"];
                $info["city_name"] = $this->getcode($info["city"])["fullname"];
                $info["area_name"] = $this->getcode($info["area"])["fullname"];
                $res[$key]["shopinfo"] = $info;
                $res[$key]["shop"] = $info;

                $res[$key]["start_time"] = date('m月d日 H:i:s',$val['start_time']);
                $res[$key]["end_time"] = date('m月d日 H:i:s',$val['end_time']);
                //判断退款
                if ($val["start_time"] - $day > $time) {
                    $res[$key]["state"] = 1;
                } else {
                    if ($val["start_time"] - $day < $time) {
                        $res[$key]["state"] = 2;
                    }
                }

                if ($val["iszx"] == 1) {
                    $xzorder = pdo_get("yzzc_sun_xzorder", array("uniacid" => $_W["uniacid"], "ordernum" => $val["ordernum"], "ispay" => 1));
                    $res[$key]["end_time"] = $xzorder["end_time"];
                    $res[$key]["day"] = $val["day"] + $xzorder["day"];
                }

                if ($set["open_xz"] == 1) {
                    if ($res[$key]["carinfo"]["open_xz"] == 1) {
                        if ($val["end_time"] - $hour > $time) {
                            $res[$key]["open_xz"] = 1;
                        } else {
                            $res[$key]["open_xz"] = 0;
                        }
                    } else {
                        $res[$key]["open_xz"] = 0;
                    }
                } else {
                    $res[$key]["open_xz"] = 0;
                }
            }
        }
        $this->return_msg(1, $res, "success");
    }

    /**
     * @return void
     * 订单详情
     */
    public function doPageUserOrderDetail()
    {
        global $_GPC, $_W;
        $where = ["uniacid" => $_W["uniacid"], "uid" => $_GPC["uid"], "display" => 1,'id'=>$_GPC['id']];
        $res = pdo_get("yzzc_sun_order",$where);
        if (!$res){
            $this->return_msg(-1,[],'订单不存在');
        }
        $set = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("istui", "tuimoney", "open_xz", "xztime",'close_time'));
        $day = $set["istui"] * 24 * 60 * 60;
        $hour = $set["xztime"] * 60 * 60;
        $time = time();

        $car_info = pdo_get("yzzc_sun_goods_sku", array("id" => $res["cid"]));
        if ($car_info['cartype']){
            $cartype = pdo_get('yzzc_sun_cartype',['uniacid'=>$_W['uniacid'],'id'=>$car_info['cartype']]);
            $car_info['car_type_name'] = $cartype['name'] ?? '';
        }

        $res["carinfo"] = $car_info;

        if ($res) {
            if ($res["usetime"]) {
                $res["usetime"] = date("Y-m-d H:i:s", $res["usetime"]);
            }
            $info = pdo_get("yzzc_sun_branch", array("id" => $res["start_shop"]), array("id", "name", "province", "city", "area",'address','shop_tel','ranges','lat','lng'));
            $info["province_name"] = $this->getcode($info["province"])["fullname"];
            $info["city_name"] = $this->getcode($info["city"])["fullname"];
            $info["area_name"] = $this->getcode($info["area"])["fullname"];
            $res["shopinfo"] = $info;
            $res["set"] = $set;
            if ($res["start_time"] - $day > $time) {
                $res["state"] = 1;
            } else {
                if ($res["start_time"] - $day < $time) {
                    $res["state"] = 2;
                }
            }
            if ($res["iszx"] == 1) {
                $xzorder = pdo_get("yzzc_sun_xzorder", array("uniacid" => $_W["uniacid"], "ordernum" => $res["ordernum"], "ispay" => 1));
                $res["end_time"] = $xzorder["end_time"];
                $res["day"] = $res["day"] + $xzorder["day"];
            }
            if ($res["return_time"]) {
                $res["return_time"] = date("Y-m-d H:i:s", $res["return_time"]);
            }
            if ($set["open_xz"] == 1) {
                if ($res["carinfo"]["open_xz"] == 1) {
                    if ($res["end_time"] - $hour > $time) {
                        $res["open_xz"] = 1;
                    } else {
                        $res["open_xz"] = 0;
                    }
                } else {
                    $res["open_xz"] = 0;
                }
            } else {
                $res["open_xz"] = 0;
            }
        }
        $this->return_msg(1, $res, "success");
    }


    /**
     * @return void
     * 订单详情
     */
    public function doPageOrderDetail()
    {
        global $_GPC, $_W;
        $where = ["uniacid" => $_W["uniacid"], "display" => 1,'id'=>$_GPC['id']];
        $res = pdo_get("yzzc_sun_order",$where);
        if (!$res){
            $this->return_msg(-1,[],'订单不存在');
        }
        $set = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("istui", "tuimoney", "open_xz", "xztime",'close_time'));
        $day = $set["istui"] * 24 * 60 * 60;
        $hour = $set["xztime"] * 60 * 60;
        $time = time();
        if ($res['is_inner'] == 1){
            $car_info = pdo_get("yzzc_sun_goods_sku", array("id" => $res["sku_id"]),['id','goods_id','sid','name','carnum','colour','structure','grarbox','displacement','num','pic','source_type','tag_id','cartype']);
            if ($car_info['cartype']){
                $cartype = pdo_get('yzzc_sun_cartype',['uniacid'=>$_W['uniacid'],'id'=>$car_info['cartype']]);
                $car_info['car_type_name'] = $cartype['name'] ?? '';
            }
        }else{
            //外调
            $car_info['name'] = $res['car_name'];
            $car_info['carnum'] = $res['carnum'];
        }


        $res["carinfo"] = $car_info;

        if ($res) {
            if ($res["usetime"]) {
                $res["usetime"] = date("Y-m-d H:i:s", $res["usetime"]);
            }
            $info = pdo_get("yzzc_sun_branch", array("id" => $res["start_shop"]), array("id", "name", "province", "city", "area",'address','shop_tel','ranges','lat','lng'));
            $info["province_name"] = $this->getcode($info["province"])["fullname"];
            $info["city_name"] = $this->getcode($info["city"])["fullname"];
            $info["area_name"] = $this->getcode($info["area"])["fullname"];
            $res["shopinfo"] = $info;
            $res["set"] = $set;
            if ($res["start_time"] - $day > $time) {
                $res["state"] = 1;
            } else {
                if ($res["start_time"] - $day < $time) {
                    $res["state"] = 2;
                }
            }
            if ($res["iszx"] == 1) {
                $xzorder = pdo_get("yzzc_sun_xzorder", array("uniacid" => $_W["uniacid"], "ordernum" => $res["ordernum"], "ispay" => 1));
                $res["end_time"] = $xzorder["end_time"];
                $res["day"] = $res["day"] + $xzorder["day"];
            }
            if ($res["return_time"]) {
                $res["return_time"] = date("Y-m-d H:i:s", $res["return_time"]);
            }
            if ($set["open_xz"] == 1) {
                if ($res["carinfo"]["open_xz"] == 1) {
                    if ($res["end_time"] - $hour > $time) {
                        $res["open_xz"] = 1;
                    } else {
                        $res["open_xz"] = 0;
                    }
                } else {
                    $res["open_xz"] = 0;
                }
            } else {
                $res["open_xz"] = 0;
            }
        }
        $this->return_msg(1, $res, "success");
    }
    /**
     * @return void
     * 申请退款
     */
    public function doPagerefund()
    {
        global $_W, $_GPC;
        $id = $_GPC["oid"];
        $uniacid = $_W["uniacid"];
        $res = pdo_update("yzzc_sun_order", array("istui" => 1), array("uniacid" => $_W["uniacid"], "id" => $id));
        if ($res) {
            $this->return_msg(1, array(), "申请成功");
        } else {
            $this->return_msg(-1, array(), "申请失败");
        }
    }

    /**
     * @return void
     * 取消退款
     */
    public function doPagerefundcancel()
    {
        global $_W, $_GPC;
        $id = $_GPC["oid"];
        $uniacid = $_W["uniacid"];
        $res = pdo_update("yzzc_sun_order", array("istui" => 0), array("uniacid" => $_W["uniacid"], "id" => $id, "status" => 2));

        if ($res) {
            $this->return_msg(1, array(), "取消成功");
        } else {
            $this->return_msg(-1, array(), "取消失败");
        }
    }

    public function doPagerefundDeposit()
    {
        global $_W, $_GPC;
        $id = $_GPC["oid"];
        $uniacid = $_W["uniacid"];
        $res = pdo_update("yzzc_sun_order", array("isdeposit" => 1), array("uniacid" => $_W["uniacid"], "id" => $id));
        if ($res) {
            $this->return_msg(1, array(), "申请成功");
        } else {
            $this->return_msg(-1, array(), "申请失败");
        }
    }

    public function doPagerefundcancelDeposit()
    {
        global $_W, $_GPC;
        $id = $_GPC["oid"];
        $uniacid = $_W["uniacid"];
        $res = pdo_update("yzzc_sun_order", array("isdeposit" => 0), array("uniacid" => $_W["uniacid"], "id" => $id));
        if ($res) {
            $this->return_msg(1, array(), "取消成功");
        } else {
            $this->return_msg(-1, array(), "取消失败");
        }
    }

    /**
     * @return void
     * 创建租车订单
     */
    public function doPageOrder()
    {
        global $_GPC, $_W;
        $cid = $_GPC["goods_id"] ?? $_GPC['cid'];
        $uid = $_GPC["uid"];
        $isorder = pdo_get("yzzc_sun_order", array("cid" => $cid, "uid" => $uid, "ispay" => 0, "isuse" => 0, "status !=" => 4), array("id"));
        $start_time = $_GPC["start_time"];
        $end_time = $_GPC["end_time"];
        $start_shop = $_GPC["start_shop"];
        $end_shop = $_GPC["end_shop"];
        $type = $_GPC["type"];
        $sku_id = $_GPC["sku_id"];
        $typeid = $_GPC["typeid"];
        $gettype = $_GPC["gettype"];
        $couponid = $_GPC["couponid"];
        $active = $_GPC["active"];
        $carinfo = pdo_get("yzzc_sun_goods", array("id" => $cid, "status" => 1, "is_del" => 0));
        $sku_info = pdo_get("yzzc_sun_goods_sku", array("id" => $sku_id, "goods_id" => $cid, "is_del" => 0));
        if ($this->CheckSku($sku_id,$cid,$start_time,$end_time) === false){
            $this->return_msg(-1,[],'库存不足');
        }

        if (empty($_GPC["driveid"])) {
            $this->return_msg(-1, array(), "请选择驾驶员！");
        }
        $drive_info = pdo_get('yzzc_sun_user_drive',["uniacid" => $_W["uniacid"],'id'=>$_GPC["driveid"]],'name');
        $user = pdo_get('yzzc_sun_user',["uniacid" => $_W["uniacid"],'id'=>$uid]);
        if ($carinfo) {
            $order_set = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("know", "long_prepay", "short_prepay", "rule",'hour_type','deposit','close_time'));
            $order_set['rule'] = htmlspecialchars_decode($order_set['rule']);
            $order_set['know'] = htmlspecialchars_decode($order_set['know']);
            $day = floor(($end_time-$start_time)/86400);
            $data = [
                'cid' => $cid,
                'sku_id' => $sku_id,
                'carnum' => $sku_info['carnum'],
                'car_name' => $sku_info['name'],
                'gettype' => $gettype,
                'type' => 1,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'start_shop' => $start_shop,
                'end_shop' => $end_shop,
                'day' => $day,
                'uid' => $uid,
                'ordernum' => date("YmdHis") . str_pad(mt_rand(1, 9999), 4, "0", STR_PAD_LEFT),
                'username' => $drive_info['name'],
                'tel' => $user['user_tel'],
                'driveid' => $_GPC["driveid"],
                'fee' => $carinfo["fee"],
                'money' => $carinfo['money'],
                'uniacid' => $_W['uniacid'],
                'createtime' => time(),
                'user_address' => $_GPC['user_address'] ?? '',
                'user_lat' => $_GPC['user_lat'],
                'user_lng' => $_GPC['user_lng'],
                'cost_money' => round($day * $carinfo['cost_money']) //成本价格
            ];
            //计算节日费用
            $festival_money = $this->checkFestival($start_time,$day,$carinfo,$cid);

            $ystotal = $data["fee"] + $data["zx_service_fee"];
            //计算超出小时费用
            $max_hour = $_GPC["end_time"] -  $_GPC["start_time"];
            $max_hour = round(floor($max_hour)%86400/3600,2);

            $beyond_hour_price = 0;
            if ($order_set['hour_type'] == 1){
                //按小时算
                $beyond_hour_price = round($data["carinfo"]["money"] / 24) * $max_hour;
            }elseif ($order_set['hour_type'] == 2){
                $max_hour = round(floor($max_hour)%86400/3600,2);
                if ($max_hour >= 4) {
                    $beyond_hour_price = 0;
                    $data['day']+=1;
                }else{
                    $beyond_hour_price = $data["carinfo"]["money"] / 2;
                }
            }

            //尊享服务费
            if ($data["open_zx_service"] == 1) {
                $data["zx_service_fee"] = $carinfo["zx_service_fee"];
            }
            $day_money = $data["money"] * $data['day'];

            //优惠劵
            if (isset($_GPC['coupon_id']) && $_GPC['coupon_id']){
                //计算订单优惠
                $coupon_id = $_GPC['coupon_id'];
                $where = " WHERE  a.uniacid=" . $_W["uniacid"] . " and a.end_time >" . time() . " and a.start_time < " . time() . " and b.isuse = 0 and a.money < " . $data['money'].' and a.id='.$coupon_id;
                $sql = "select a.id,a.title,a.money  from " . tablename("yzzc_sun_coupon") . "a " . "left join" . tablename("yzzc_sun_coupon_get") . "b on b.cid=a.id and b.uid= " . "{$uid}.{$where}";
                $ky_coupon = pdo_fetch($sql);
                if (!$ky_coupon){
                    $this->return_msg(-1,[],'优惠劵使用错误');
                }
                $day_money = $day_money - $ky_coupon['money'];
                if ($day_money <= 0){
                    $this->return_msg(-1,[],'支付金额错误');
                }

                $data["coupon_money"] = $ky_coupon["money"];
                $data["coupon"] = $_GPC['coupon_id'];
            }

            $data['service_fee'] = $carinfo["service_fee"] * $data['day'];//基础服务费
            $data["festival_money"] = $festival_money;//节假日费用
            $data["deposit_money"] = $order_set['deposit'];//押金
            $data["total_money"] = $data['prepay_money'] = $day_money + $data['service_fee'] + $beyond_hour_price + $ystotal+$festival_money + $data["zx_service_fee"];//总金额
            if ($data["carinfo"]['depositway'] == 1){
                //单独使用押金
                $data["deposit_money"] = $carinfo['deposit'];
            }

            //计算订单过期时间
            if($order_set['close_time'] > 0){
                $data['expired_date'] = time() + ($order_set['close_time'] * 60);
            }

//            if ($type == 2) {
//                $taocan = pdo_get("yzzc_sun_taocan", array("id" => $typeid));
//                if ($taocan["day"] > $day) {
//                    $this->return_msg(-1, array(), "该车辆至少" . $taocan["day"] . "天起订");
//                }
//                $data["money"] = $carinfo["money"] - $carinfo["money"] * ($taocan["money"] / 100);
//                $data["money"] = sprintf("%.2f", $data["money"]);
//            } else {
//                if ($active == 1) {
//                    $data["active"] = $active;
//                    $data["money"] = $carinfo["act_money"];
//                } else {
//                    $data["money"] = $carinfo["money"];
//                }
//            }

            //$user = pdo_get("yzzc_sun_user", array("id" => $uid), array("all_integral", "now_integral"));
//            $levelinfo = $this->mylevel($user["all_integral"]);
//            if ($levelinfo["level_privileges"] == 2) {
//                $data["service_fee"] = 0;
//            } else {
//                $data["service_fee"] = $carinfo["service_fee"];
//            }
//            if ($levelinfo["level_privileges"] == 3) {
//                $data["end_time"] = $end_time + $levelinfo["delay"] * 60 * 60;
//            }


            //使用积分
//            $data["integral_money"] = 0;
//            if ($_GPC["open_integral"] == 1) {
//                if ($user["now_integral"] >= $_GPC["integral"]) {
//                    $data["integral_money"] = $_GPC["integral_money"];
//                    $data["integral"] = $_GPC["integral"];
//                    if ($data["integral"] > 0) {
//                        $this->scoreAct($uid, 4, -$data["integral"]);
//                    }
//                }
//            }


//            if ($order_set["short_prepay"] > 0 && $type == 1) {
//                $data["prepay_money"] = $order_set["short_prepay"];
//            } else {
//                if ($order_set["long_prepay"] > 0 && $type == 2) {
//                    $data["prepay_money"] = $order_set["long_prepay"];
//                } else {
//                    $data["prepay_money"] = $_GPC["total_money"] - $_GPC["deposit_money"];
//                }
//            }

            pdo_insert("yzzc_sun_order", $data);
            $oid = pdo_insertid();
            include_once IA_ROOT . "/addons/" . $_W["current_module"]["name"] . "/inc/func/distribution.php";
            $user = pdo_get("yzzc_sun_user", array("id" => $uid));
            $distribution = new Distribution();
            $distribution->order_id = $oid;
            $distribution->money = $data["prepay_money"];
            $distribution->userid = $user["openid"];
            $distribution->ordertype = $type;
            $distribution->computecommission();
            if ($oid) {
                $this->return_msg(1, $oid, "success");
            }
        } else {
            $this->return_msg(-1, array(), "车辆不存在");
        }
    }

    /**
     * @param $start_time
     * @param $day
     * @param $carinfo
     * @param $cid
     * @return int|mixed
     * 计算节日费用
     */
    function checkFestival($start_time,$day,$car_info,$cid){
        global $_W;
        $all_day = [];
        $i = 0;
        while ($i <= $day) {
            array_push($all_day, date("Y-m-d", trim($start_time) + $i * 24 * 60 * 60));
            $i++;
        }
        $money = 0;
        if ($car_info["subscribe_duration"]) {
            $car_info["spec"] = pdo_fetchall("select * from " . tablename("yzzc_sun_specprice") . " where uniacid =" . $_W["uniacid"] . " and gid = " . $cid . " order by spec asc");
            foreach ($car_info["spec"] as $key => $value) {
                foreach ($all_day as $k => $v) {
                    if ($value["spec"] == $v) {
                        $money += $value["price"];
                        array_push($spec, $value);
                        unset($all_day[$k]);
                    }
                }
            }
        }
        return $money;
    }

    /**
     * @return void
     * 租客取车
     */
    public function doPageGetcar()
    {
        global $_GPC, $_W;
        $oid = $_GPC["oid"];
        $res = pdo_get("yzzc_sun_order", array("uniacid" => $_W["uniacid"], "id" => $oid,'uid'=>$_GPC['uid']));
        if ($res["ispay"] == 1 && $res["isuse"] == 0) {
            $data["isuse"] = 1;
            $data["usetime"] = time();
            $data["username"] = $_GPC["username"];
            $data["tel"] = $_GPC["tel"];
            $data["status"] = 3;
            $up = pdo_update("yzzc_sun_order", $data, array("id" => $oid));
            if ($up) {
                $this->return_msg(1, array(), "取车成功");
            } else {
                $this->return_msg(-1, array(), "取车失败");
            }
        } else {
            $this->return_msg(-1, array(), "该订单无法取车，请先核对订单");
        }
    }



    /**
     * @return void
     * 取消订单
     */
    public function doPageCancel()
    {
        global $_GPC, $_W;
        $oid = $_GPC["oid"];
        $res = pdo_get("yzzc_sun_order", array("uniacid" => $_W["uniacid"], "id" => $oid,'uid'=>$_GPC['uid']));
        if ($res["ispay"] == 0 && $res["isuse"] == 0) {
            $data["status"] = 4;
            $up = pdo_update("yzzc_sun_order", $data, array("id" => $oid));
            pdo_update("yzzc_sun_coupon_get", ["isuse" => 0, "usetime" => 0], array("uid" => $res["uid"], "cid" => $res["coupon"]));
            if ($up) {
                $this->return_msg(1, array(), "取消成功");
            } else {
                $this->return_msg(-1, array(), "取消失败");
            }
        } else {
            $this->return_msg(-1, array(), "该订单已支付无法取消");
        }
    }


    public function doPageAdminInfo()
    {
        global $_GPC, $_W;
        if ($_GPC["uid"]) {
            $user = pdo_get("yzzc_sun_user", array("id" => $_GPC["uid"]), array("isadmin"));
            $day = strtotime(date("Y-m-d", time()));
            if ($user["isadmin"] == 1) {
                $data["todayorder"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where createtime >" . $day . " and uniacid = " . $_W["uniacid"]);
                $todayordermoney = pdo_fetch("SELECT SUM(prepay_money) as money FROM " . tablename("yzzc_sun_order") . "where createtime >" . $day . " and uniacid = " . $_W["uniacid"] . " and (status = 2 or status =3 or status = 0)");
                $todayordermoney1 = pdo_fetch("SELECT SUM(total_money) as money FROM " . tablename("yzzc_sun_xzorder") . "where createtime >" . $day . " and uniacid = " . $_W["uniacid"] . " and ispay = 1");
                $data["todayordermoney"] = $todayordermoney["money"] + $todayordermoney1["money"];
                $data["todayuser"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_user") . "where time >" . $day . " and uniacid = " . $_W["uniacid"]);
                $data["allshop"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_branch") . "where uniacid = " . $_W["uniacid"]);
                $data["allcar"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_goods") . "where is_del = 0 and uniacid = " . $_W["uniacid"]);
                $data["allorder"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"]);
                $data["todaysign"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_signlog") . "where createtime >" . $day . " and uniacid = " . $_W["uniacid"]);
                $data["admininfo"] = 0;
                $this->return_msg(1, $data);
            } else {
                $branchadmin = pdo_get("yzzc_sun_branch_admin", array("uid" => $_GPC["uid"]));
                if ($branchadmin) {
                    $data["admininfo"] = $branchadmin;
                    $data["branchinfo"] = pdo_get("yzzc_sun_branch", array("id" => $branchadmin["bid"]));
                    $data["todayorder"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where createtime >" . $day . " and uniacid = " . $_W["uniacid"] . " and start_shop =" . $branchadmin["bid"]);
                    $todayordermoney = pdo_fetch("SELECT SUM(prepay_money) as money FROM " . tablename("yzzc_sun_order") . "where createtime >" . $day . " and uniacid = " . $_W["uniacid"] . " and (status = 2 or status =3 or status = 0) and start_shop =" . $branchadmin["bid"]);
                    $todayordermoney1 = pdo_fetch("SELECT SUM(xzmoney) as money FROM " . tablename("yzzc_sun_order") . "where createtime >" . $day . " and uniacid = " . $_W["uniacid"] . " and (status = 2 or status =3 or status = 0) and start_shop =" . $branchadmin["bid"]);
                    $data["todayordermoney"] = $todayordermoney["money"] + $todayordermoney1["money"];
                    $data["todayuser"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_user") . "where time >" . $day . " and uniacid = " . $_W["uniacid"]);
                    $data["allshop"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_branch") . "where uniacid = " . $_W["uniacid"]);
                    $data["allcar"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_goods") . "where is_del = 0 and uniacid = " . $_W["uniacid"] . " and sid =" . $branchadmin["bid"]);
                    $data["allorder"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop =" . $branchadmin["bid"]);
                    $data["todaysign"] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_signlog") . "where createtime >" . $day . " and uniacid = " . $_W["uniacid"]);
                    $this->return_msg(1, $data);
                } else {
                    $this->return_msg(-1, array(), "您还不是管理员哦");
                }
            }
        } else {
            $this->return_msg(-1, array(), "uid不能为空");
        }
    }

    /**
     * @return string
     * 获取订单号
     */
    function getOrderNo(){
        return date("YmdHis") . str_pad(mt_rand(1, 9999), 4, "0", STR_PAD_LEFT);
    }

    /**
     * @return void
     * 调用微信支付
     */
    public function doPageOrderarr()
    {

        global $_GPC, $_W;
        $oid = intval($_GPC["oid"]);
        $pay_type = intval($_GPC["pay_type"]);
        if ($pay_type == 2){
            //线下支付
            $order = pdo_get("yzzc_sun_order", ["uniacid" => $_W["uniacid"], "id" => $oid, "status" => 1]);
            $total_fee = $order['total_money'] ;
            $order_set = pdo_get("yzzc_sun_order_set", ["uniacid" => $_W["uniacid"]], ["zlsz",'shuttle_type','shuttle_commission']);
            //计算交还车原收益
            $shuttle_commission = 0;
            if ($order_set['shuttle_type'] == 1){
                //订单总额百分比
                $shuttle_commission =  round(($order_set['shuttle_commission'] / 100) * $order['prepay_money'],2);
            }
            if ($order_set['shuttle_type'] == 2){
                //订单总额固定值
                $shuttle_commission = $order_set['shuttle_commission'];
            }

            //更新订单状态
            $res = pdo_update("yzzc_sun_order", [
                "ispay" => 1,
                "paytime" => time(),
                "status" => 2,
                'prepay_money' => $total_fee,
                'shuttle_commission' => $shuttle_commission
            ], ["uniacid" => $_W["uniacid"], "id" => $oid]);

            //更新订单时间
            $data1 = [
                'start_time' => $order["start_time"],
                'end_time' => $order["end_time"],
                'carnum' => $order["carnum"],
                'order_id' => $oid,
                'goods_id' => $order['cid'],
                'sku_id' => $order["sku_id"],
                'uniacid' => $_W["uniacid"]
            ];
            pdo_insert("yzzc_sun_ordertime", $data1);

            //更新优惠劵
            if ($order['coupon'] > 0){
                pdo_update("yzzc_sun_coupon_get", array("isuse" => 1, "usetime" => time()), array("cid" => $order['coupon'], "uid" => $order['uid']));
            }

            $shop = pdo_get("yzzc_sun_branch", ["uniacid" => $_W["uniacid"], "id" => $order["start_shop"]]);

            //获取短信配置，发生租车短信
            $set = pdo_get("yzzc_sun_msg_set", ["uniacid" => $_W["uniacid"]]);
            if ($set["open"] == 1) {
                $mobile = $shop["shop_tel"];
                include_once IA_ROOT . "/addons/yzzc_sun/api/TencentCloud/sendSms.php";
                set_time_limit(0);
                $sendid = $set["dayu_templatecode"];
                if ($sendid != "") {
                    sendSms($set["dayu_accesskey"], $set["dayu_accesskeysecret"], $mobile, $set["dayu_signname"], $sendid);
                }
            }
        }else{
            include_once "wxpay.php";
            $out_trade_no = rand(10000, 99999) . time() . rand(10000, 99999) . $oid;
            $orderinfo = pdo_get("yzzc_sun_order", array("id" => $oid, "uniacid" => $_W["uniacid"]), array("prepay_money", "deposit_money"));
            pdo_update("yzzc_sun_order", array("out_trade_no" => $out_trade_no), array("id" => $oid));
            $total_fee = $orderinfo["prepay_money"];
            $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
            $appid = $appData["appid"];
            $mch_id = $appData["mchid"];
            $key = $appData["wxkey"];
            $openid = $_GPC["openid"];
            $total_fee = $total_fee * 100;
            $body = "订单支付";
            $notify_url = $_W["siteroot"] . "addons/yzzc_sun/notify.php";
            $attach = $_W["uniacid"] . "@@@0@@@" . $oid;
            $wxpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $attach, $notify_url);
            $ret = $wxpay->pay();
            $this->return_msg(1, $ret);
        }
    }
    /**
     * @return void
     * 续租支付
     */
    public function doPageOrderarrxz()
    {
        include_once "wxpay.php";
        global $_GPC, $_W;
        $oid = intval($_GPC["oid"]);
        $out_trade_no = rand(10000, 99999) . time() . rand(10000, 99999) . $oid;
        $orderinfo = pdo_get("yzzc_sun_xzorder", array("id" => $oid, "uniacid" => $_W["uniacid"]), array("total_money"));
        pdo_update("yzzc_sun_xzorder", array("out_trade_no" => $out_trade_no), array("id" => $oid));
        $total_fee = $orderinfo["total_money"];
        $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
        $appid = $appData["appid"];
        $mch_id = $appData["mchid"];
        $key = $appData["wxkey"];
        $openid = $_GPC["openid"];
        $total_fee = $total_fee * 100;
        $body = "订单支付";
        $notify_url = $_W["siteroot"] . "addons/yzzc_sun/notify.php";
        $attach = $_W["uniacid"] . "@@@1@@@" . $oid;
        $wxpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $attach, $notify_url);
        $ret = $wxpay->pay();
        $this->return_msg(1, $ret);
    }

    function createPaySign($result)
    {
        global $_W;
        $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
        $keys = $appData["wxkey"];
        $data = array("appId" => $result["appid"], "timeStamp" => (string)time(), "nonceStr" => $result["nonce_str"], "package" => "prepay_id=" . $result["prepay_id"], "signType" => "MD5");
        ksort($data, SORT_ASC);
        $stringA = '';
        foreach ($data as $key => $val) {
            $stringA .= "{$key}={$val}&";
        }
        $signTempStr = $stringA . "key=" . $keys;
        $signValue = strtoupper(md5($signTempStr));
        $data["paySign"] = $signValue;
        $data["prepay_id"] = $result["prepay_id"];
        return $data;
    }

    public function doPagePaysuccess()
    {
        global $_GPC, $_W;
        $oid = $_GPC["oid"];
        if ($oid) {
            $orderInfo = pdo_get("yzzc_sun_order", array("id" => $oid, "uniacid" => $_W["uniacid"]));
            $system = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]), array("order_template_id"));
            if ($system["order_template_id"]) {
                $user = pdo_get("yzzc_sun_user", array("id" => $orderInfo["uid"]), array("openid"));
                $car = pdo_get("yzzc_sun_goods", array("id" => $orderInfo["cid"]));
                $data["keyword1"]["value"] = $_GPC["shopname"];
                $data["keyword2"]["value"] = $car["name"];
                $data["keyword3"]["value"] = $car["carnum"];
                $data["keyword4"]["value"] = date("Y年m月d日 H时i分s秒", $orderInfo["start_time"]);
                $res = $this->doPageSendtem($user["openid"], $system["order_template_id"], "yzzc_sun/pages/order/order", $_GPC["formId"], $data);
            }
            $this->return_msg(1, array("oid" => $oid, "sid" => $orderInfo["start_shop"], "res" => $res));
        }
    }

    function httpRequest($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
            $headerArray = ["Content-type:application/json;charset='utf-8'", 'Accept:application/json'];
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function doPageToken()
    {
        global $_W;
        $system = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]), array("appid", "appsecret", "token_expires_in", "token"));
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $system["appid"] . "&secret=" . $system["appsecret"];
        $info = $this->httpRequest($url);
        $info = json_decode($info, true);
        pdo_update("yzzc_sun_system", array("token" => $info["access_token"], "token_expires_in" => time() + 7000), array("uniacid" => $_W["uniacid"]));
        $token = $info["access_token"];
        return $token;
    }

    public function doPageSendtem($openid, $template_id, $page, $form_id, $data)
    {
        $token = $this->doPageToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $token;
        $info["touser"] = $openid;
        $info["template_id"] = $template_id;
        $info["page"] = $page;
        $info["form_id"] = $form_id;
        $info["data"] = $data;
        $res = $this->httpRequest($url, json_encode($info));
        return $res;
    }

    public function doPageQrpic()
    {
        global $_W, $_GPC;
        $set = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]), array("appid", "appsecret", "token_expires_in", "token"));
        $system["appid"] = $set["appid"];
        $system["appsecret"] = $set["appsecret"];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $system["appid"] . "&secret=" . $system["appsecret"];
        $info = $this->httpRequest($url);
        $info = json_decode($info, true);
        $token = $info["access_token"];
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $token;
        $data["scene"] = $_GPC["scene"];
        $data["page"] = $_GPC["page"];
        $data["width"] = 430;
        $jpg = $this->httpRequest($url, json_encode($data));
        if ($jpg) {
            $newpath = IA_ROOT . "/attachment/";
            $filename = time() . rand(1000, 9999) . ".jpg";
            $file = fopen($newpath . $filename, "w");
            fwrite($file, $jpg);
            fclose($file);
            @(require_once IA_ROOT . "/framework/function/file.func.php");
            @($filenames = $filename);
            @file_remote_upload($filenames);
            $this->return_msg(1, array("img" => $filename));
        } else {
            $this->return_msg(-1, array(), "小程序码错误");
        }
    }

    public function doPageDelimg()
    {
        global $_GPC;
        $file = IA_ROOT . "/attachment/" . $_GPC["img"];
        if (!unlink($file)) {
            echo "Error deleting {$file}";
        } else {
            echo "Deleted {$file}";
        }
    }

    private function curlPost($url, $postFields)
    {
        $postFields = json_encode($postFields);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec($ch);
        if (false == $ret) {
            $result = curl_error($ch);
        } else {
            $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 " . $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
        curl_close($ch);
        return $result;
    }

    public function SendYtxSmsbl($sendid = '', $sms = array(), $params = '')
    {
        global $_W, $_GPC;
        $postArr = array("account" => $sms["ytx_apiaccount"], "password" => $sms["ytx_apipass"], "msg" => $sendid, "params" => $params, "report" => "true");
        $url = "http://smssh1.253.com/msg/variable/json";
        $result = $this->curlPost($url, $postArr);
        return $result;
    }

    public function SendYtxSms($msg, $sms = array(), $mobile = '')
    {
        $postArr = array("account" => $sms["api_account"], "password" => $sms["api_psw"], "msg" => urlencode($msg), "phone" => $mobile, "report" => "true");
        $url = "http://smssh1.253.com/msg/send/json";
        $result = $this->curlPost($url, $postArr);
        return $result;
    }

    public function doPageBranchCarlsit()
    {
        global $_W, $_GPC;
        $type = $_GPC["type"] ? $_GPC["type"] : 1;
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        if ($_GPC["sid"] > 0) {
            $where["sid"] = $_GPC["sid"];
        }
        $where["uniacid"] = $_W["uniacid"];
        $where["status"] = $type == 1 ? $type : 3;
        $where["is_del"] = 0;
        $res = pdo_getall("yzzc_sun_goods", $where, array(), '', array("status asc"), array($page, $length));
        $this->return_msg(1, $res);
    }

    public function doPageDoCar()
    {
        global $_W, $_GPC;
        $info = pdo_get("yzzc_sun_goods", array("id" => $_GPC["id"]));
        if ($_GPC["type"] == 1) {
            if ($info["status"] == 3) {
                $data["status"] = 1;
            } else {
                $this->return_msg(-1, array(), "当前车辆无法上架");
            }
        } else {
            if ($_GPC["type"] == 2) {
                if ($info["status"] == 1) {
                    $data["status"] = 3;
                } else {
                    $this->return_msg(-1, array(), "当前车辆无法下架");
                }
            } else {
                if ($_GPC["type"] == 3) {
                    if ($info["status"] == 1 || $info["status"] == 3) {
                        $data["is_del"] = 1;
                    } else {
                        $this->return_msg(-1, array(), "当前车辆无法删除");
                    }
                } else {
                }
            }
        }
        $res = pdo_update("yzzc_sun_goods", $data, array("id" => $_GPC["id"], "uniacid" => $_W["uniacid"]));
        if ($res) {
            $this->return_msg(1);
        } else {
            $this->return_msg(-1, array(), "error");
        }
    }

    public function doPageBranchOrder()
    {
        global $_GPC, $_W;
        $type = $_GPC["type"] ? $_GPC["type"] : 1;
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        $where["type"] = $type;
        if ($_GPC["sid"] > 0) {
            $where["start_shop"] = $_GPC["sid"];
        }
        $where["uniacid"] = $_W["uniacid"];
        $where["display"] = 1;
        $where["status"] = $_GPC["status"];
        $res = pdo_getall("yzzc_sun_order", $where, array(), '', array("status asc"), array($page, $length));
        foreach ($res as $key => $val) {
            $res[$key]["carinfo"] = pdo_get("yzzc_sun_goods", array("id" => $val["cid"]));
            if ($res) {
                $info = pdo_get("yzzc_sun_branch", array("id" => $val["start_shop"]), array("id", "name", "province", "city", "area"));
                $info["province_name"] = $this->getcode($info["province"])["fullname"];
                $info["city_name"] = $this->getcode($info["city"])["fullname"];
                $info["area_name"] = $this->getcode($info["area"])["fullname"];
                $res[$key]["shop"] = $info;
                if ($val["iszx"] == 1) {
                    $xzorder = pdo_get("yzzc_sun_xzorder", array("uniacid" => $_W["uniacid"], "ordernum" => $val["ordernum"], "ispay" => 1));
                    $res[$key]["return_time"] = $xzorder["return_time"];
                    $res[$key]["end_time"] = $xzorder["end_time"];
                    $res[$key]["day"] = $val["day"] + $xzorder["day"];
                }
            }
        }
        $this->return_msg(1, $res, "success");
    }

    public function doPageReturnCar()
    {
        global $_GPC, $_W;
        $order = pdo_get("yzzc_sun_order", array("id" => $_GPC["id"], "uniacid" => $_W["uniacid"]));
        if ($order["iszx"] == 1) {
            $xzorder = pdo_get("yzzc_sun_xzorder", array("ordernum" => $order["ordernum"], "uniacid" => $_W["uniacid"]));
        }
        if ($order["status"] == 3) {
            $res = pdo_update("yzzc_sun_order", array("status" => 0, "return_time" => time()), array("id" => $_GPC["id"], "uniacid" => $_W["uniacid"]));
            if ($res) {
                $res1 = pdo_delete("yzzc_sun_ordertime", array("carnum" => $order["carnum"], "start_time" => $order["start_time"], "uniacid" => $_W["uniacid"], "end_time" => $order["end_time"]));
                if ($xzorder["ispay"] == 1) {
                    $res2 = pdo_delete("yzzc_sun_ordertime", array("carnum" => $order["carnum"], "start_time" => $xzorder["start_time"], "uniacid" => $_W["uniacid"], "end_time" => $xzorder["end_time"]));
                }
                $zlsz = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]), array("zlsz"));
                if ($zlsz["zlsz"] == 0) {
                    pdo_update("yzzc_sun_goods", array("status" => 1), array("uniacid" => $_W["uniacid"], "carnum" => $order["carnum"]));
                }
                include_once IA_ROOT . "/addons/" . $_W["current_module"]["name"] . "/inc/func/distribution.php";
                $distribution = new Distribution();
                $distribution->order_id = $_GPC["id"];
                $distribution->ordertype = $order["type"];
                $distribution->settlecommission();
                $this->return_msg(1, array(), "还车成功");
            } else {
                $this->return_msg(-1, array(), "还车失败！");
            }
        } else {
            $this->return_msg(-1, array(), "当前车辆无法还车！");
        }
    }

    public function doPagePlugin()
    {
        global $_W, $_GPC;
        $type = intval($_GPC["type"]);
        $uniacid = $_W["uniacid"];
        if ($type == 1) {
            if (pdo_tableexists("yzzc_sun_distribution_set")) {
                $set = pdo_get("yzzc_sun_distribution_set", array("uniacid" => $uniacid));
                if ($set) {
                    if ($set["status"] > 0) {
                        echo json_encode($set);
                    } else {
                        echo 2;
                    }
                } else {
                    echo 2;
                }
            } else {
                echo 2;
            }
        } else {
            if ($type == 2) {
                if (pdo_tableexists("yzzc_sun_plugin_scoretask_system")) {
                    $system = pdo_get("yzzc_sun_plugin_scoretask_system", array("uniacid" => $_W["uniacid"]));
                    if ($system["is_show"] == 1) {
                        echo json_encode($system);
                    } else {
                        echo 2;
                    }
                } else {
                    echo 2;
                }
            } else {
                echo 2;
            }
        }
    }
    public function doPageUserDistributors()
    {
        global $_W, $_GPC;
        $type = intval($_GPC["type"]);
        $uniacid = $_W["uniacid"];
        if ($type == 1) {
            if (pdo_tableexists("yzzc_sun_distribution_set")) {
                $set = pdo_get("yzzc_sun_distribution_set", array("uniacid" => $uniacid));
                if ($set) {
                    $this->return_msg(1,$set,'获取成功');
                } else {
                    $this->return_msg(-1,[],'销售不存在');
                }
            } else {
                $this->return_msg(-1,[],'不存在表');
            }
        } else {
            if ($type == 2) {
                if (pdo_tableexists("yzzc_sun_plugin_scoretask_system")) {
                    $system = pdo_get("yzzc_sun_plugin_scoretask_system", array("uniacid" => $_W["uniacid"]));
                    if ($system["is_show"] == 1) {
                        echo json_encode($system);
                    } else {
                        echo 2;
                    }
                } else {
                    echo 2;
                }
            } else {
                echo 2;
            }
        }
    }

    public function doPageTest()
    {
        global $_W, $_GPC;
        echo "aaaaaaaaaaaaa";
        include_once IA_ROOT . "/addons/" . $_W["current_module"]["name"] . "/inc/func/distribution.php";
        $distribution = new Distribution();
        $distribution->order_id = $_GPC["oid"];
        $distribution->money = 2000;
        $distribution->userid = "o3W0Y4xbxds5g0-bbf9qFzulgp6Q";
        $distribution->ordertype = 3;
        $distribution->computecommission();
    }

    /**
     * @return void
     * 添加身份证号
     */
    public function doPageAddIdCard()
    {
        global $_W, $_GPC;
//        $set = pdo_get("yzzc_sun_order_set", array("uniacid" => $_W["uniacid"]));
//        $zj = explode(",", $set["zj"]);

        if (empty($_GPC["sfcode"])) {
            $this->return_msg(-1, array(), "请输入身份信息");
        }
        if (empty($_GPC["phone"])) {
            $this->return_msg(-1, array(), "请输入手机号");
        }

        $user_drive = pdo_get('yzzc_sun_user_drive', ['uniacid' => $_W['uniacid'], 'uid' => $_GPC['uid'],'sfcode'=>$_GPC['sfcode']]);
        if ($user_drive) {
            $this->return_msg(-1, array(), "该身份证已添加认证");
        }

        $data = [
            'time' => time(),
            'uniacid' => $_W['uniacid'],
            'uid' => $_GPC['uid'],
            'name' => $_GPC['name'],
            'phone' => $_GPC['phone'],
            'sfcode' => $_GPC['sfcode']
        ];

        if (!pdo_get('yzzc_sun_user_drive', ['uniacid' => $_W['uniacid'], 'uid' => $_GPC['uid'],'is_mr'=>1])){
            $data['is_mr'] = 1;
        }
        $this->checkIdCard($data["sfcode"], $data["name"]);

        $res = pdo_insert("yzzc_sun_user_drive", $data);
        pdo_update('yzzc_sun_user',['user_name'=>$_GPC['name']],[ 'id' => $_GPC['uid']]);
        if ($res) {
            pdo_update('yzzc_sun_user',['is_auth'=>1],['id'=>$_GPC['uid']]);
            $this->return_msg(1, array(), "success");
        } else {
            $this->return_msg(-1, array(), "添加失败！");
        }
    }

    /**
     * @return void
     * 上传身份证正反图片
     */
    public function doPageAddIdCardImg()
    {
        global $_W, $_GPC;
        if (empty($_GPC["sfimg"]) || empty($_GPC["sfimgfan"]) || empty($_GPC['uid'])) {
            $this->return_msg(-1, array(), "请输入身份信息");
        }
        $where = ['uniacid' => $_W['uniacid'], 'uid' => $_GPC['uid']];
        $user_drive = pdo_get('yzzc_sun_user_drive', $where);

        $arr = $this->checkIdCardImg($_GPC["sfimg"]);
        $id_card_info = $arr['data']['info'];

        if (!$id_card_info['name'] || !$id_card_info['number']) {
            $this->return_msg(-1, array(), "上传的身份证图片出错");
        }

        $user_drive_ = pdo_get('yzzc_sun_user_drive', ['uniacid' => $_W['uniacid'], 'uid' => $_GPC['uid'],'sfcode'=>$id_card_info['number']]);
        if ($user_drive_) {
            $this->return_msg(-1, array(), "该身份证已添加认证");
        }

        $data = [
            'time' => time(),
            'uniacid' => $_W['uniacid'],
            'uid' => $_GPC['uid'],
            'sfimg' => $_GPC["sfimg"],
            'sfimgfan' => $_GPC["sfimgfan"],
            'name' => $id_card_info['name'],
            'sfcode' => $id_card_info['number']
        ];

        if(!$user_drive){
            $data['is_mr'] = 1;
            $res = pdo_insert("yzzc_sun_user_drive", $data);
            if ($res) {
                pdo_update('yzzc_sun_user',['is_auth'=>1,'user_name'=>$id_card_info['name']],['id'=>$_GPC['uid']]);
                $this->return_msg(1, array(), "success");
            } else {
                $this->return_msg(-1, array(), "上传失败！");
            }
        }
    }

    /**
     * @return void
     * 添加驾驶证信息
     */
    public function doPageAddLicense()
    {
        global $_W, $_GPC;
        if (empty($_GPC["jsimg"]) || empty($_GPC["jsimgfan"]) || empty($_GPC['uid'])) {
            $this->return_msg(-1, array(), "请上传驾驶证正反面图片");
        }
        $where = ['uniacid' => $_W['uniacid'], 'uid' => $_GPC['uid']];
        $user_drive = pdo_get('yzzc_sun_user_drive', $where);
        if (!$user_drive) {
            $this->return_msg(-1, array(), "请先添加身份证信息");
        }

//        $arr = $this->checkLicense($_GPC["jsimg"]);
//
//        $id_card_info = $arr['data']['result']['page_a'];
//
//        if ($id_card_info['name'] != $user_drive['name']) {
//            $this->return_msg(-1, array(), "上传的驾驶证图片和填写姓名不一致");
//        }
//
//        if ($id_card_info['id'] != $user_drive['sfcode']) {
//            $this->return_msg(-1, array(), "上传的驾驶证图片和填写身份证号码不一致");
//        }
//
//        $data = [
//            'jsimg' => $_GPC["jsimg"],
//            'jsimgfan' => $_GPC["jsimgfan"],
//            'license_data' => serialize($arr['data']['result'])
//        ];

        $data = [
            'jsimg' => $_GPC["jsimg"],
            'jsimgfan' => $_GPC["jsimgfan"],
            'license_data' => ''
        ];
        $res = pdo_update("yzzc_sun_user_drive", $data, $where);
        if ($res) {
            $this->return_msg(1, array(), "success");
        } else {
            $this->return_msg(-1, array(), "上传失败！");
        }
    }

    /**
     * @param $idcard
     * @param $name
     * @return true
     * 检验身份证是否一致
     */
    function checkIdCard($idcard, $name)
    {
        $msectime = $this->msectime();
        $appid = 'Ej3kBb15sBFoEfKo';

        // 使用函数发送POST请求
        $url = "https://api.shumaidata.com/v4/id_card/check";
        $data_ = [
            'appid' => $appid,
            'timestamp' => $msectime,
            'sign' => $this->getSign($appid, $msectime),
            'idcard' => $idcard,
            'name' => $name,
        ];

        $res = $this->sendPostRequestWithStatusCode($url, $data_);

        if ($res['statusCode'] !== 200) {
            $this->return_msg(-1, [], $res['msg']);
        }
        if ($res['data']['code'] == 400) {
            $this->return_msg(-1, [], $res['data']['msg']);
        }
        return true;
    }

    /**
     * @param $image_url
     * @return mixed
     * 第三方获取身份证图片信息
     */
    function checkIdCardImg($image_url)
    {
        $timestamp = time() * 1000;

        $url = "https://api.shumaidata.com/v2/idcard/ocr";
        $appid = 'Ej3kBb15sBFoEfKo';
        $data_ = [
            'appid' => $appid,
            'timestamp' => $timestamp,
            'sign' => $this->getSign($appid, $timestamp),
            'url' => $image_url
        ];
        $res = $this->sendPostRequestWithStatusCode($url, $data_);
        if ($res['statusCode'] !== 200) {
            $this->return_msg(-1, [], $res['msg']);
        }
        if ($res['data']['code'] == 400) {
            $this->return_msg(-1, [], $res['data']['msg']);
        }
        return $res['data'];
    }

    /**
     * @param $image_url
     * @return mixed
     * 第三方获取驾照图片信息
     */
    function checkLicense($image_url)
    {
        $timestamp = time() * 1000;

        $url = "https://api.shumaidata.com/v2/driving_licence/ocr";
        $appid = 'Ej3kBb15sBFoEfKo';
        $data_ = [
            'appid' => $appid,
            'timestamp' => $timestamp,
            'sign' => $this->getSign($appid, $timestamp),
            'url' => $image_url
        ];
        $res = $this->sendPostRequestWithStatusCode($url, $data_);
        if ($res['statusCode'] !== 200) {
            $this->return_msg(-1, [], '上传图片错误，请联系管理员');
        }
        if ($res['data']['code'] == 400) {
            $this->return_msg(-1, [], $res['data']['msg']);
        }
        return $res['data'];
    }

    /**
     * @return void
     * 腾讯云os  上传图片
     */
    public function doPageTencentOsUpload()
    {
        //$img = 'https://car-1257066132.cos.ap-nanjing.myqcloud.com/file/2023-10-24/img/808981216960513615594.jpg';
        //$imageInfo = getimagesize($img);
        //$base64 = "" . chunk_split(base64_encode(file_get_contents($img)));
        //$this->dd('data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img))));
        $up_types = array("image/jpg", "image/jpeg", "image/png", "image/pjpeg", "image/x-png");
        $max_file_size = 4000000;
        if (!is_uploaded_file($_FILES["file"]["tmp_name"])) {
            $this->return_msg(-1, [], '图片不存在');
        }

        $file = $_FILES["file"];
        if ($max_file_size < $file["size"]) {
            $this->return_msg(-1, [], '图片尺寸不能超过10Mb');
        }

        if (!in_array($file["type"], $up_types)) {
            $this->return_msg(-1, [], '文件类型不符!只允许上传jpg,png图片');

        }
        require __DIR__ . '/tencent-php/vendor/autoload.php';
        $secretId = "AKIDFMNEvOjtsVvAB5rifbN2b2WxADAtT4Yy";
        $secretKey = "Ocw7ACA1kJ3oZOQVcYdaUOUadl8jHkBU";
        $region = "ap-nanjing";
        $bucket = 'car-1257066132';
        $pinfo = pathinfo($file["name"]);
        $ftype = $pinfo["extension"];
        $destination = str_shuffle(rand(11111, 99999) . time() . rand(111111, 999999)) . "." . $ftype;
        $cosClient = new Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials' => array(
                    'secretId' => $secretId,
                    'secretKey' => $secretKey
                )
            )
        );
        $local_path = $file["tmp_name"]; //保存到用户本地路径
        $path = 'file/' . date('Y-m-d') . '/img/' . $destination;
        try {
            $cosClient->upload($bucket, $path, fopen($local_path, 'rb'));
            $this->return_msg(1, ['url' => 'https://car-1257066132.cos.ap-nanjing.myqcloud.com/' . $path]);

        } catch (\Exception $e) {
            $this->return_msg(-1, [], '上传图片失败，请联系管理员');
        }
    }

    /**
     * @return void
     * 车辆品牌列表
     */
    public function doPageBrandLists(){
        global $_W;
        $data = pdo_getall('yzzc_sun_carbrand',['uniacid' => $_W['uniacid']]);
        $this->return_msg(1, $data);
    }

    /**
     * @return void
     * 车辆标签列表
     */
    public function doPageTagLists(){
        global $_W;
        $data = pdo_getall('yzzc_sun_car_tag',['uniacid' => $_W['uniacid']]);
        $this->return_msg(1, $data);
    }

    /**
     * @return void
     * 车辆标签列表
     */
    public function doPageCarTypeLists(){
        global $_W,$_GPC;
        $data = pdo_getall('yzzc_sun_cartype',['uniacid' => $_W['uniacid']]);
        foreach ($data as $key => $val){
            $sid = $_GPC["sid"];
            $stime = $_GPC["stime"];
            $etime = $_GPC["etime"];
            $lat = $_GPC["lat"];
            $lng = $_GPC['lng'];

            $where = 'a.is_del = 0 and a.audit_status = 1 and b.status = 1 and a.status =1 and a.uniacid='.$_W["uniacid"];
            //分类
            $where.=' and a.cartype='.$val["id"];

            //商户
            if ($_GPC["sid"]) {
                $where.=' and a.sid='.$sid;
            }
            //品牌
            if ($_GPC["brand_id"]) {
                $where.=' and a.brand_id='.$_GPC["brand_id"];
            }
            //标签
            if ($_GPC["tag_id"]) {
                $where.= " and (a.tag_id = {$_GPC["tag_id"]} or a.tag_id like '%{$_GPC["tag_id"]}%' or a.tag_id like '%,{$_GPC["tag_id"]}%' or a.tag_id like '%{$_GPC["tag_id"]},%')";
            }
            $sort = $_GPC["sort"];
            $order = '';
            if ($_GPC['order'] == 'default' || empty($_GPC['order'])){
                $order = 'a.hot asc,id desc';
            }elseif ($_GPC['order'] == 'money'){
                $order = 'a.money '.$sort;
            }elseif ($_GPC['order'] == 'distance'){
                $order = 'distance '.$sort;
            }
            $sql = "select  a.id,a.name,a.structure,a.grarbox,a.num,a.pic,a.money,a.tag_id,a.brand_id,a.cartype,b.name as branch_name,b.lng,b.lat,( 6371 * acos (cos ( radians(" . $lat . ") )* cos( radians( b.lat ) ) * cos( radians( b.lng ) - radians(" . $lng . ") )+ sin ( radians(" . $lat . ") )* sin( radians( b.lat ) ) ) ) AS distance from " . tablename("yzzc_sun_goods") . "a " . "left join" . tablename("yzzc_sun_branch") . "b on b.id=a.sid  where ".$where. " order by ".$order;
            $car_list = pdo_fetchall($sql);;

            foreach ($car_list as $k => $value){
                $tags = [];
                if ($value['tag_id']){
                    $tags = pdo_fetchall('select * from '.tablename('yzzc_sun_car_tag').' where uniacid='.$_W['uniacid'].' and id in('.$value['tag_id'].')') ?? [];
                }
                $car_list[$k]['tags'] = $tags;

                if ($value['pic']){
                    $pic = explode(',',$value['pic']);
                    $car_list[$k]['pic'] = $pic[0] ?? '';
                }
                if ($value['brand_id']){
                    $brand = pdo_get('yzzc_sun_car_tag',['uniacid'=>$_W['uniacid'],'id'=>$value['brand_id']]);
                }
                $car_list[$k]['brand_name'] = $brand['name'] ?? '';

                if ($value['cartype']){
                    $cartype = pdo_get('yzzc_sun_cartype',['uniacid'=>$_W['uniacid'],'id'=>$value['cartype']]);
                }
                $car_list[$k]['car_type_name'] = $cartype['name'] ?? '';

                //sku
                $sku = pdo_getall('yzzc_sun_goods_sku',['goods_id'=>$value['id'],'is_del'=>0]);
                $sku_id = 0;
                foreach ($sku as  $sku_val){
                    if ($this->CheckSku($sku_val['id'],$value['id'],$stime,$etime) === false){
                        continue;
                    }else{
                        $sku_id = $sku_val['id'];
                        $carnum = $sku_val['carnum'];
                        $colour = $sku_val['colour'];
                        $displacement = $sku_val['displacement'];
                        break;
                    }
                }
                if ($sku_id == 0){
                    unset($car_list[$k]);
                }
                $car_list[$k]['sku_id'] = $sku_id;
                $car_list[$k]['carnum'] = $carnum ?? '';
                $car_list[$k]['colour'] = $colour ?? '';
                $car_list[$k]['displacement'] = $displacement ?? '';

            }
            $val['car_list'][] = $car_list;

            $min = 0;
            if (count($car_list) > 0){
                $records = array_column($car_list, 'money');
                $min = min($records);
                if ($min === false){
                    $min = 0;
                }
            }
            $val['min_money'] = $min;
            $new_data[] = $val;
        }
        $this->return_msg(1, $new_data ?? []);
    }

    /**
     * @return void
     * 商家入驻配置
     */
    public function doPageStoreConfig(){
        global $_W,$_GPC;
        $store_config = pdo_get('yzzc_sun_store_config',['uniacid'=>$_W['uniacid']]);
        $this->return_msg(1, $store_config, '获取成功');
    }

    /**
     * @return void
     * 商家个人信息
     */
    public function doPageStoreDetail(){
        global $_GPC, $_W;
        $uid = $_GPC['uid'];
        $type = $_GPC['type'];
        if (!$uid || !$type){
            $this->return_msg(-1,[],'参数错误');
        }

        $this->checkStore($uid,$type);

        if ($type == 1){
            //商户
            $branch_admin = pdo_get("yzzc_sun_branch_admin", array("uid" => $_GPC["uid"]));
            $data["admin_info"] = $branch_admin;

            $branch_info = pdo_get("yzzc_sun_branch", array("id" => $branch_admin["bid"]));
            $branch_info['member_start_time'] = $branch_info['member_start_time'] ? date('Y-m-d H:i:s',$branch_info['member_start_time']) :'';
            $branch_info['member_end_time'] = $branch_info['member_end_time'] ? date('Y-m-d H:i:s',$branch_info['member_end_time']) :'';
            $data['shop_info'] = $branch_info;

            //非平台门店。统计收益
            $total_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_branch_income") . "where uniacid = " . $_W["uniacid"] . " and branch_id =" . $branch_info["id"]);
            $wait_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_branch_income") . "where uniacid = " . $_W["uniacid"] . " and branch_id = {$branch_info["id"]} and status = 0");
            $finish_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_branch_income") . "where uniacid = " . $_W["uniacid"] . " and branch_id = {$branch_info["id"]} and status = 1");
            $data['branch_income'] = [
                'total_amount' => $total_amount['money'] ?? 0.00,
                'wait_amount' => $wait_amount['money'] ?? 0.00,
                'finish_amount' => $finish_amount['money'] ?? 0.00,
                'balance' => $branch_info['balance'] ?? 0.00,
            ];

            //待处理
            $wait_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop = {$branch_info["id"]} and status in (1,2)");

            //进行中
            $processing_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop = {$branch_info["id"]} and status = 3");

            //已完成
            $finish_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop = {$branch_info["id"]} and status = 0");
            //已取消
            $cancel_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop = {$branch_info["id"]} and status = 4");
            $data['order'] = [
                'wait_order' => $wait_order ?? 0,
                'processing_order' => $processing_order ?? 0,
                'finish_order' => $finish_order ?? 0,
                'cancel_order' => $cancel_order ?? 0,
            ];

            //当天出租
            $car_hire = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . " where status = 2  and uniacid = {$_W["uniacid"]} and start_shop ={$branch_admin["bid"]}");

            $car_number = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_goods") . " where  uniacid = {$_W["uniacid"] } and sid ={$branch_admin["bid"]} and is_del = 0 and status = 1");
            $data['car'] = [
                'hire_car' => $car_hire===false? 0 :$car_hire,
                'free_time_car' => $car_number - $car_hire ?? 0
            ];

            $car_lists = pdo_getall('yzzc_sun_goods',['sid'=>$branch_info['id'],'uniacid'=>$_W["uniacid"],'is_del'=>0],['name','money','cost_money','pic','id','audit_status','audit_remark','status']);
            foreach ($car_lists as $key => $val){
                //销量
                $sales = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . " where uniacid = {$_W["uniacid"]} and start_shop ={$branch_admin["bid"]} and status != 4 and cid = {$val['id']}");
                $car_lists[$key]['sales'] = $sales ===false ? 0 : $sales;

                //库存
                $car_lists[$key]['inventory'] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_goods_sku") . " where uniacid = {$_W["uniacid"]} and sid ={$branch_admin["bid"]} and is_del = 0 and goods_id = {$val['id']}") ?? 0;
            }
            $data['car_list'] = $car_lists;
            $this->return_msg(1, $data);
        }elseif ($type == 2){
            //个体
            $branch_admin = pdo_get("yzzc_sun_store", array("uid" => $_GPC["uid"]));
            $data["admin_info"] = $branch_admin;

            //非平台门店。统计收益
            $total_amount = pdo_fetchcolumn("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_branch_income") . "where uniacid = " . $_W["uniacid"] . " and  type = 3 and store_id = " . $branch_admin["store_id"]);
            $wait_amount = pdo_fetchcolumn("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_branch_income") . "where uniacid = " . $_W["uniacid"] . " and store_id = {$branch_admin["store_id"]} and status = 0");

            $data['branch_income'] = [
                'total_amount' => $total_amount ?? 0.00,
                'wait_amount' => $wait_amount ?? 0.00,
                'finish_amount' => $branch_admin['billing_amount'],
                'balance' => $branch_admin['balance'],
            ];
//
//            //待处理
//            $wait_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop = {$branch_info["id"]} and status in (1,2)");
//
//            //进行中
//            $processing_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop = {$branch_info["id"]} and status = 3");
//
//            //已完成
//            $finish_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop = {$branch_info["id"]} and status = 0");
//            //已取消
//            $cancel_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop = {$branch_info["id"]} and status = 4");
//            $data['order'] = [
//                'wait_order' => $wait_order ?? 0,
//                'processing_order' => $processing_order ?? 0,
//                'finish_order' => $finish_order ?? 0,
//                'cancel_order' => $cancel_order ?? 0,
//            ];

            $goods_ids =  pdo_fetchall("SELECT id FROM " . tablename("yzzc_sun_goods_sku") . " where  uniacid = {$_W["uniacid"] } and store_id ={$branch_admin["store_id"]} and is_del = 0");

            $car_hire = 0;
            $car_number = 0;
            if ($goods_ids){
                $goods_ids = array_column($goods_ids,'id');
                $goods_ids = implode(',',$goods_ids);
                //当天出租
                $car_hire = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . " where status = 2  and uniacid = {$_W["uniacid"]} and sku_id in ({$goods_ids})");

                $car_number = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_goods_sku") . " where  uniacid = {$_W["uniacid"] } and store_id ={$branch_admin["store_id"]} and is_del = 0");
            }
            $data['car'] = [
                'hire_car' => $car_hire,
                'free_time_car' => $car_number - $car_hire
            ];

            $car_lists = pdo_getall('yzzc_sun_goods',['store_id'=>$branch_admin['store_id'],'uniacid'=>$_W["uniacid"],'is_del'=>0],['name','money','cost_money','pic','id','audit_status','audit_remark','status']);
            foreach ($car_lists as $key => $val){
                //销量
                $sales = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . " where uniacid = {$_W["uniacid"]} and status != 4 and cid = {$val['id']}");
                $car_lists[$key]['sales'] = $sales ===false ? 0 : $sales;

                //库存
                $car_lists[$key]['inventory'] = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_goods_sku") . " where uniacid = {$_W["uniacid"]} and sid ={$branch_admin["bid"]} and is_del = 0 and goods_id = {$val['id']}") ?? 0;
            }
            $data['car_list'] = $car_lists;
            $this->return_msg(1, $data);
        }

    }



    /**
     * @param $uid
     * @param $branch_id
     * @return true
     * 商户检测
     */
    function checkStore($uid,$type)
    {
        global $_W,$_GPC;
        $user = pdo_get('yzzc_sun_user',['id'=>$uid,'uniacid'=>$_W['uniacid']]);
        if (!$user){
            $this->return_msg(-1,[],'会员尚未注册');
        }

        if ($type == 1){
            //商家
            $branch_admin = pdo_get("yzzc_sun_branch_admin", array("uid" => $uid));
            if (!$branch_admin){
                $this->return_msg(-1, array(), "您还不是管理员哦");
            }
        }
        if ($type == 2){
            $store_info = pdo_get("yzzc_sun_store", array("uid" => $uid));
            if (!$store_info){
                $this->return_msg(-1, array(), "身份不存在");
            }
            if ($store_info['is_disable'] == 0){
                $this->return_msg(-1, [], '您已被禁用');
            }
        }
//        if ($branch_admin && $branch_id == 0){
//            $branch_id = array_column($branch_admin,'bid');
//        }else{
//            $branch_id = explode(',',$branch_id);
//        }

//        $branch = pdo_getall("yzzc_sun_branch", array("id in" => $branch_id));
//        if (!$branch){
//            $this->return_msg(-1, array(), "门店不存在");
//        }

        /*if ($branch['status'] != 1){
            $this->return_msg(-1, array(), "门店已关闭，请联系管理员");
        }*/
        return true;
    }

    /**
     * @return void
     * 门店订单列表
     */
    public function doPageStoreOrderLists(){
        global $_W,$_GPC;
        $uid = $_GPC['uid'];
        $branch_id = $_GPC['branch_id'];
        if (!$uid || !$branch_id){
            $this->return_msg(-1,[],'参数错误');
        }
        $status = $_GPC['status'];
        $this->checkStore($uid,$branch_id);
        $where = [
            'start_shop' => $branch_id,
            'uniacid' => $_W['uniacid'],
        ];
        if ($status == 3){
            $where['status in'] = '2,3';
        }else{
            if ($status != ''){
                $where['status'] = $status;
            }
        }

        $order_list = pdo_getall('yzzc_sun_order',$where,['id','cid','sku_id','gettype','start_time','end_time','status','prepay_money','total_money','start_shop','end_shop','day']);
        if ($order_list){
            foreach ($order_list as $key => $value){
                $sku = pdo_get('yzzc_sun_goods_sku',['id'=>$value['sku_id']],['id','colour','structure','grarbox','displacement','num','pic']);
                $order_list[$key]['carinfo'] = $sku;

                $shop = pdo_get('yzzc_sun_branch',['id'=>$value['start_shop']],['id','type','name','province','city','area','address','lng','lat','shop_tel']);
                $order_list[$key]['shopinfo'] = $shop;
            }
        }
        $this->return_msg(1,$order_list,'获取成功');
    }

    /**
     * @return void
     *收益列表
     */
    public function doPageStoreIncomeLists(){
        global $_W,$_GPC;
        //非平台门店。统计收益
        $uid = $_GPC['uid'];
        $branch_id = $_GPC['branch_id'];
        if (!$uid || !$branch_id){
            $this->return_msg(-1,[],'参数错误');
        }

        $this->checkStore($uid,$branch_id);
        $total_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_branch_income") . "where uniacid = " . $_W["uniacid"] . " and branch_id =" . $branch_id);
        $wait_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_branch_income") . "where uniacid = " . $_W["uniacid"] . " and branch_id = {$branch_id} and status = 0");
        $finish_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_branch_income") . "where uniacid = " . $_W["uniacid"] . " and branch_id = {$branch_id} and status = 1");
        $data['branch_income'] = [
            'total_amount' => $total_amount['money'] ?? 0.00,
            'wait_amount' => $wait_amount['money'] ?? 0.00,
            'finish_amount' => $finish_amount['money'] ?? 0.00,
        ];
        $log = pdo_getall('yzzc_sun_branch_income',['branch_id'=>$branch_id,'uniacid'=>$_W["uniacid"]],['order_id','total','platform_fee','amount','status']);
        if ($log){
            foreach ($log as $key => $value){
                $sql = "select a.id,a.ordernum,b.name,b.carnum,b.colour,b.structure,b.grarbox,b.displacement,b.num,b.pic from " . tablename("yzzc_sun_order") . "a " . "left join" . tablename("yzzc_sun_goods_sku") . "b on b.id=a.sku_id where a.id = {$value['order_id']}  and  a.uniacid = " . $_W["uniacid"];
                $list = pdo_fetch($sql);
                $log[$key]["car"] = $list;
            }
        }
        $data['log'] = $log;
        $this->return_msg(1, $data,'操作成功');
    }

    /**
     * @return void
     * 提现申请
     */
    public function doPageStorePayout(){
        global $_W,$_GPC;
        $uid = $_GPC['uid'];
        $branch_id = $_GPC['branch_id'];
        $bank_title = $_GPC['bank_title'];
        $bank_number = $_GPC['bank_number'];
        $bank_name = $_GPC['bank_name'];
        $amount = $_GPC['amount'];
        if (!$uid || !$branch_id || !$bank_title || !$bank_number || !$bank_name || !$amount){
            $this->return_msg(-1,[],'参数错误');
        }
        $this->checkStore($uid,$branch_id);

        $branch_info = pdo_get('yzzc_sun_branch',['id'=>$branch_id]);
        if ($branch_info['balance'] < $amount){
            $this->return_msg(-1, [],'余额不足，无法提现');
        }

        $platform_fee = 0;
        $data = [
            'uid' => $uid,
            'branch_id' => $branch_id,
            'uniacid' => $_W['uniacid'],
            'total' => $amount,
            'amount' => $amount - $platform_fee,
            'platform_fee' => $platform_fee,
            'bank_name' => $bank_name,
            'bank_number' => $bank_number,
            'bank_title' => $bank_title,
            'type' => $branch_info['type'],
            'createtime' => time()
        ];
        $result = pdo_insert('yzzc_sun_branch_payout',$data);
        $update_branch = pdo_update('yzzc_sun_branch',['balance'=>$branch_info['balance'] - $amount],['id'=>$branch_id]);
        if ($result && $update_branch){
            $this->return_msg(1, [],'提现成功，等待审核');
        }
        $this->return_msg(-1, [],'提现失败，请联系管理员');
    }

    /**
     * @return void
     * 申请列表
     */
    public function doPageStorePayoutLists(){
        global $_W,$_GPC;
        $uid = $_GPC['uid'];
        $branch_id = $_GPC['branch_id'];
        if (!$uid || !$branch_id ){
            $this->return_msg(-1,[],'参数错误');
        }
        $this->checkStore($uid,$branch_id);

        $data = [
            'uid' => $uid,
            'branch_id' => $branch_id,
            'uniacid' => $_W['uniacid'],
        ];
        $result = pdo_getall('yzzc_sun_branch_payout',$data,['id','uid','branch_id','total','platform_fee','amount','status','remark','bank_name','bank_number','bank_title','createtime']);
        if ($result){
            array_walk($result,function ($v){
                $v['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
            });
        }
        $this->return_msg(1, $result,'操作成功');
    }

    /**
     * @return void
     * 申请列表
     */
    public function doPageStorePayoutStatus(){
        global $_W,$_GPC;

        $id = $_GPC['id'];
        if (!$id){
            $this->return_msg(-1,[],'参数错误');
        }
        $data = [
            'id' => $id,
            'uniacid' => $_W['uniacid'],
        ];
        $result = pdo_get('yzzc_sun_branch_payout',$data,['id','uid','total','platform_fee','amount','status','remark','bank_name','bank_number','bank_title','createtime']);
        $result['createtime'] = date('Y-m-d H:i:s',$result['createtime']);
        $this->return_msg(1, $result,'操作成功');
    }
    /**
     * @return void
     * 商家入驻审核
     */
    public function doPageStoreApply(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }
        if (empty($_GPC['name']) || empty($_GPC['mobile'])){
            $this->return_msg(-1, [], '资料不完善');
        }
        if (!pdo_get('yzzc_sun_user',['id'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']])){
            $this->return_msg(-1, [], '会员尚未注册');
        }

        $store_config = pdo_get('yzzc_sun_store_config',['uniacid'=>$_W['uniacid']]);
        if ($store_config['is_open_apply'] != 1){
            $this->return_msg(-1, [], '平台未开启商家入驻申请');
        }

//        $user_drive = pdo_get('yzzc_sun_user_drive',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);
//        if (!$user_drive){
//            $this->return_msg(-1, [], '请先完成实名认证');
//        }

        $data = [
            'uniacid'=>$_W['uniacid'],
            'uid' => trim($_GPC['uid']),
            'name' => trim($_GPC['name']),
            'mobile' => trim($_GPC['mobile']),
            'province' => trim($_GPC['province']),
            'city' => trim($_GPC['city']),
            'area' => trim($_GPC['area']),
            'lng' => trim($_GPC['lng']),
            'lat' => trim($_GPC['lat']),
            'title' => trim($_GPC['title']),
            'ranges' => trim($_GPC['ranges']),
            'cert_img' => trim($_GPC['cert_img']),
            'pic' => trim($_GPC['pic']),
            'address' => trim($_GPC['address']),
            'service_tel' => $_GPC['mobile'],
            'createtime' => time(),
            'type' => 1
        ];
        if ($store_config['is_fee'] == 1){
            $data['pay_status'] = 0;
        }else{
            $data['pay_status'] = 2;
        }

        $store = pdo_get('yzzc_sun_store',['uid'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']]);
//        if ($store){
//            $this->return_msg(-1, [], '已存在入驻身份，请勿重新申请');
//        }

        try {
            pdo_fetchall('START TRANSACTION');//启动一个新事务
            $result = pdo_insert('yzzc_sun_store_apply',$data);
            if (!$result){
                pdo_fetchall('ROLLBACK');//事务回滚
                $this->return_msg(-1, [],'入驻失败');
            }
            $store_id = pdo_insertid();
            if ($result){
                if ($data['pay_status'] == 0){
                    //创建入驻费用
                    $order_data = [
                        'uid' => $_GPC['uid'],
                        'order_no' => $this->getOrderNo(),
                        'uniacid' => $_W['uniacid'],
                        'name' => $data['name'],
                        'mobile' => $data['mobile'],
                        'amount' => $store_config['amount'],
                        'createtime' => time(),
                        'store_id' => $store_id
                    ];
                    if (pdo_get('yzzc_sun_store_order',['store_id'=>$store_id,'member_id'=>0])){
                        $this->return_msg(-1, [], '入驻订单已创建，请勿重复创建');
                    }

                    pdo_insert('yzzc_sun_store_order',$order_data);
                    $oid = pdo_insertid();
                    if ($oid){
                        pdo_fetchall('COMMIT');//事务提交
                        $this->return_msg(1, ['pay_status'=>$data['pay_status'],'oid'=>$oid], '申请成功，等待审核');
                    }else{
                        pdo_fetchall('ROLLBACK');//事务回滚
                        $this->return_msg(-1, [], '入驻订单创建失败，请联系管理员');
                    }
                }else{
                    pdo_fetchall('COMMIT');//事务提交
                    $this->return_msg(1, ['pay_status'=>$data['pay_status'],'oid'=>0], '申请成功，等待审核');
                }
            }
            pdo_fetchall('ROLLBACK');//事务回滚
            $this->return_msg(-1, [], '申请失败，请联系管理员');
        }catch (Exception $exception){
            pdo_fetchall('ROLLBACK');//事务回滚
            $this->return_msg(-1, [], '申请失败，请联系管理员');
        }
    }

    /**
     * @return void
     * 个人入驻
     */
    public function doPagePersonalStoreApply(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }
        if (empty($_GPC['name']) || empty($_GPC['mobile'])){
            $this->return_msg(-1, [], '资料不完善');
        }
        if (!pdo_get('yzzc_sun_user',['id'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']])){
            $this->return_msg(-1, [], '会员尚未注册');
        }

        $store_config = pdo_get('yzzc_sun_store_config',['uniacid'=>$_W['uniacid']]);
        if ($store_config['is_open_apply'] != 1){
            $this->return_msg(-1, [], '平台未开启入驻申请');
        }

        $user_drive = pdo_get('yzzc_sun_user_drive',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);
        if (!$user_drive){
            $this->return_msg(-1, [], '请先完成实名认证');
        }

        $data = [
            'uniacid'=>$_W['uniacid'],
            'uid' => trim($_GPC['uid']),
            'name' => trim($_GPC['name']),
            'mobile' => trim($_GPC['mobile']),
            'province' => trim($_GPC['province']),
            'address' => trim($_GPC['address']),
            'city' => trim($_GPC['city']),
            'area' => trim($_GPC['area']),
            'lng' => trim($_GPC['lng']),
            'lat' => trim($_GPC['lat']),
            'type' => 2,
            'pay_status' => 2,
            'createtime' => time(),
            'driving_license' => trim($_GPC['driving_license']),
            'id_license' => trim($_GPC['id_license']),
            'sy_insurance' => trim($_GPC['sy_insurance']),
            'jq_insurance' => trim($_GPC['jq_insurance'])
        ];

//        $store = pdo_get('yzzc_sun_store',['uid'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']]);
//        if ($store){
//            $this->return_msg(-1, [], '请勿重复申请');
//        }

        $result = pdo_insert('yzzc_sun_store_apply',$data);
        if ($result){
            $this->return_msg(1, [], '申请成功，等待审核');
        }
        $this->return_msg(-1, [], '申请失败，请联系管理员');
    }
    /**
     * @return void
     * 商家入驻详情
     */
    public function doPageStoreApplyDetail(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }
        $data = pdo_get('yzzc_sun_store_apply',['uid'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']]);
        if (!$data){
            $this->return_msg(-1, [], '未申请入驻');
        }
        $data['pic'] = $data['pic'] ? explode(',',$data['pic']) : [];
        if ($data['type'] == 1){
            unset($data['driving_license'],$data['id_license'],$data['sy_insurance'],$data['jq_insurance'],$data['updatetime']);
        }
        $this->return_msg(1, $data, '操作成功');
    }

    /**
     * @return void
     * 申请状态
     */
    public function doPageStoreApplyStatus(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }
        $data = pdo_get('yzzc_sun_store_apply',['uid'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']],['status','pay_status','remark']);
        if (!$data){
            $this->return_msg(-1, [], '未申请入驻');
        }
        $this->return_msg(1, $data, '操作成功');
    }

    /**
     * @return void
     * 创建入驻费用订单
     */
    public function doPageCreateStoreOrder(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }

        $store_config = pdo_get('yzzc_sun_store_config',['uniacid'=>$_W['uniacid']]);
        if ($store_config['is_fee'] != 1){
            $this->return_msg(-1, [], '入驻无需支付入驻费用');
        }
        $store = pdo_get('yzzc_sun_store',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);
        if ($store['status'] !=1){
            $this->return_msg(-1, [], '入驻审核未通过');
        }

        $store_order = pdo_get('yzzc_sun_store_order',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);
        if ($store_order){
            $this->return_msg(-1, [], '入驻订单已创建');
        }

        $user = pdo_get('yzzc_sun_user',['id'=>$_GPC['uid'],'uniacid'=>$_W['uniacid']]);
        if (!$user){
            $this->return_msg(-1, [], '会员尚未注册');
        }

        $data = [
            'uid' => $_GPC['uid'],
            'order_no' => $this->getOrderNo(),
            'uniacid' => $_W['uniacid'],
            'name' => $store['name'],
            'mobile' => $store['mobile'],
            'amount' => $store_config['amount'],
            'createtime' => time()
        ];

        pdo_insert('yzzc_sun_store_order',$data);
        $oid = pdo_insertid();
        if ($oid){
            $this->return_msg(1, $oid, '创建成功');
        }
        $this->return_msg(-1, [], '创建失败，请联系管理员');
    }

    /**
     * @return void
     * 入驻商家订单支付
     */
    public function doPagePayStoreOrder()
    {
        include_once "wxpay.php";
        global $_GPC, $_W;
        $oid = intval($_GPC["oid"]);
        $out_trade_no = rand(10000, 99999) . time() . rand(10000, 99999) . $oid;
        $order_info = pdo_get("yzzc_sun_store_order", array("order_id" => $oid, "uniacid" => $_W["uniacid"]), array("amount"));
        if (!$order_info){
            $this->return_msg(-1, [],'订单不存在');
        }
        if ($order_info['status'] == 1){
            $this->return_msg(-1, [],'订单已支付');
        }

        pdo_update("yzzc_sun_store_order", array("out_trade_no" => $out_trade_no), array("order_id" => $oid));

        $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
        $appid = $appData["appid"];
        $mch_id = $appData["mchid"];
        $key = $appData["wxkey"];
        $openid = $_GPC["openid"];
        $total_fee = $order_info["amount"] * 100;

        $body = "商家入驻订单支付";
        $notify_url = $_W["siteroot"] . "addons/yzzc_sun/notify.php";

        //3 支付商家入驻订单
        $attach = $_W["uniacid"] . "@@@2@@@" . $oid;
        $wxpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $attach, $notify_url);

        $ret = $wxpay->pay();
        $this->return_msg(1, $ret);
    }

    /**
     * @return void
     * 上传车辆
     */
    public function doPageUploadCar(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid']) || !isset($_GPC['cartype']) || !isset($_GPC['type'])){
            $this->return_msg(-1, [], '参数不全');
        }

        $source_type = $_GPC['type'];
//        $branch_info = pdo_get('yzzc_sun_branch',['uniacid'=>$_W['uniacid'],'id'=>$_GPC['branch_id']]);
//        if (!$branch_info){
//            $this->return_msg(-1, [], '入驻审核未通过');
//        }
        //$store_info =
        $spec = $_GPC['spec'] ?? '';
        if (!$spec){
            $this->return_msg(-1, [], '车辆详细信息必填');
        }
//        if (!$_GPC['money']){
//            $this->return_msg(-1, [], '请输入车辆租金');
//        }
        $spec = json_decode(html_entity_decode($spec),true);
        $data = [
//            'uid' => $_GPC['uid'],
//            'store_id' => $branch_info['store_id'],
//            'sid' => $branch_info['id'],
//            'store_name' => $branch_info['name'],
//            'source_type' => $branch_info['type'],
            'uniacid' => $_W['uniacid'],
            'name' => trim($_GPC['car_name']),
            'structure' => trim($_GPC['structure']),
            'grarbox' => trim($_GPC['grarbox']),
            'num' => trim($_GPC['num']),
            'brand_id' => trim($_GPC['brand_id']),
            'cartype' => trim($_GPC['cartype']),
            'pic' => trim($_GPC['pic']),
            //'money' => trim($_GPC['money']),
            'audit_status' => 0,
            'createtime' => time(),
        ];

        if ($source_type == 2){
            //个体
            $store = pdo_get('yzzc_sun_store',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);

            if (!$store){
                $this->return_msg(-1, [], '身份不存在');
            }
            if ($store['is_disable'] == 0){
                $this->return_msg(-1, [], '您已被禁用');
            }
            $data['source_type'] = 3;
            $data['store_id'] = $store['store_id'];
            $data['store_name'] = $store['name'];
            $data['sid'] = 0;
        }else{

            //商家
            $bid = pdo_get('yzzc_sun_branch_admin',['uniacid'=>$_W['uniacid'],'uid'=>$_GPC['uid']]);
            if (!$bid){
                $this->return_msg(-1, [], '门店管理员身份不存在');
            }
            $branch_admin = pdo_get('yzzc_sun_branch',['uniacid'=>$_W['uniacid'],'id'=>$bid]);
            $data['store_id'] = 0;
            $data['sid'] = $branch_admin['id'];
            $data['source_type'] = 2;
        }

        $result = pdo_insert('yzzc_sun_goods',$data);
        $goods_id = pdo_insertid();
        if ($goods_id){
            foreach ($spec as $key => $value) {
                $sku = [
                    'carnum' => $value['car_num'],
                    'colour' => $value['car_color'],
                    'displacement' => $value['displacement'],
                    'goods_id' => $goods_id
                ];
                unset($data['audit_status']);
                $sku = array_merge($data,$sku);
                pdo_insert('yzzc_sun_goods_sku', $sku);
            }
        }
        if ($result){
            $this->return_msg(1, [], '创建成功');
        }
        $this->return_msg(-1, [], '创建失败，请联系管理员');
    }

    public function doPage()
    {

    }

    /**
     * @return void
     * 预订下单
     */
    public function doPageCreateBookingOrder()
    {
        global $_W,$_GPC;
        $uid = $_GPC['uid'];
        if (!$uid){
            $this->return_msg(-1,'','会员ID必传');
        }
        $dis = pdo_get('yzzc_sun_distribution_promoter',['uid' => $uid]);
        if (!$dis){
            $this->return_msg(-1,'','销售身份不存在');
        }
        $is_inner1 = $_GPC['is_inner'];
        $exterior_number = $_GPC['car_number'];
        $name = $_GPC['name'];
        $mobile = $_GPC['mobile'];
        $start_time = strtotime($_GPC['start_time']);
        $end_time = strtotime($_GPC['end_time']);
        $money = $_GPC['money'];
        $fee = $_GPC['fee'];
        $deposit_money = $_GPC['deposit_money'];
        $start_shop = $_GPC['start_shop'];
        $is_give_car = $_GPC['is_give_car'];//是否送车，如果送车，则省略送车步骤

        if (!$_GPC['start_time']) {
            $this->return_msg(-1, '', '请输入租车时间');
        }
        if ($is_inner1 == 2 && empty($exterior_number)) {
            $this->return_msg(-1, '', '外调车型请输入车牌号');
        }

        if ($is_inner1 == 2 && empty($start_shop)) {
            $this->return_msg(-1, '', '外调车型请选择发车门店');
        }
        if (!$name) {
            $this->return_msg(-1, '', '请输入客户姓名电话');
        }

//        $cle = $end_time - $start_time; //得出时间戳差值
//        $day = floor($cle / 3600 / 24);
//        $hour = floor(($cle % (3600 * 24)) / 3600);  //%取余
//        if ($hour >= 4){
//            //大于4小时算一天
//            $day+=1;
//        }elseif($hour < 4 && $hour > 0){
//            //小于4小时 但是大于0 算半天
//            $day+=0.5;
//        }

        $car_num = $exterior_number;

        $data = [
            'uniacid' => $_W['uniacid'],
            'is_inner' => $is_inner1,
            'uid' => 0,
            'carnum' => $car_num,
            'type'  => 1,
            'day' => 0,
            'createtime' => time(),
            'username' => $name,
            'tel' => $mobile,
            'ordernum' => date("YmdHis") . str_pad(mt_rand(1, 9999), 4, "0", STR_PAD_LEFT),
            'start_time' => $start_time,
            'source_type' => 2,
            'status' => 2,
            'money' => $money,
            'total_money' => number_format($money,2,'.',''),
            'prepay_money' => number_format($money,2,'.',''),
            'gettype' => $_GPC['gettype'],
            'car_name' => trim($_GPC['car_name']),
            'pay_type' => 2, //线下收款
            'distribution_id' => $uid, //绑定销售ID
            'user_lat' => $_GPC['user_lat'],
            'user_lng' => $_GPC['user_lng'],
            'user_address' => $_GPC['user_address'],
            'shuttle_id' => $_GPC['shuttle_id'] ?? 0,
            'shuttle_name' => $_GPC['shuttle_name'] ?? '',
            'is_give_car' => $is_give_car
        ];
        if ($is_give_car == 1){
            $data['status'] = 3;
        }
        $store_income = [];
        if ($is_inner1 == 1) {
//            $sku_id = $_GPC['sku_id'];
            $sku = pdo_get('yzzc_sun_goods_sku', ['carnum' => $data['carnum']]);
            if (!$sku){
                $this->return_msg(-1,'','自有车辆无匹配车型');
            }

            $goods = pdo_get('yzzc_sun_goods',['id' => $sku['goods_id']]);
            $cid = $sku['goods_id'];
            $car_num = $sku['carnum'];
            //门店
            $start_shop = $end_shop = $goods['sid'];
            $sku_id = $sku['id'];
            $data['car_name'] = $sku['name'];
            $data['carnum'] = $car_num;
            $data['store_id'] = $goods['store_id'];
            if ($goods['store_id'] > 0){
//                  是否是个人车主车辆
                $store_info = $goods = pdo_get('yzzc_sun_store',['store_id' => $sku['store_id']]);
                if (!$store_info){
                    pdo_fetchall('ROLLBACK');//事务回滚
                    $this->return_msg(-1,'','预订失败');
                }
                //创建收益
                $platform_fee = round($data['prepay_money'] * ($store_info['platform_fee'] / 100),2);
                $store_income = [
                    'branch_id' => $start_shop,
                    'store_id' => $goods['store_id'],
                    'uniacid' => $store_info['uniacid'],
                    'total' => $data['prepay_money'],
                    'branch_cost' => $platform_fee,
                    'amount' => $data['prepay_money'] - $platform_fee,
                    'createtime' => time(),
                ];
            }
        }else{
            $start_shop = $end_shop = $_GPC['start_shop'];
            $sku_id = $cid =  0;
        }

        $data['cid'] = $cid;
        $data['sku_id'] = $sku_id;
        $data['start_shop'] = $start_shop;
        $data['end_shop'] = $start_shop;

        //检测是否存在重复预订
//        $this->isOrder($data['sku_id'],$data['carnum'],$end_time,$start_time);
        try {
            pdo_fetchall('START TRANSACTION');//启动一个新事务
            if ($data['gettype'] == 2){
                $zlsz = pdo_get("yzzc_sun_order_set", ["uniacid" => $_W["uniacid"]], ["zlsz",'shuttle_type','shuttle_commission']);
                //计算交还车原收益
                $shuttle_commission = 0;
                if ($zlsz['shuttle_type'] == 1){
                    //订单总额百分比
                    $shuttle_commission =  round(($zlsz['shuttle_commission'] / 100) * $data['prepay_money'],2);
                }
                if ($zlsz['shuttle_type'] == 2){
                    //订单总额固定值
                    $shuttle_commission = $zlsz['shuttle_commission'];
                }
                $data['shuttle_commission'] = $shuttle_commission;
            }

            pdo_insert('yzzc_sun_order',$data);
            $order_id = pdo_insertid();
            if (!$order_id){
                pdo_fetchall('ROLLBACK');//事务回滚
                $this->return_msg(-1,'','预订失败');
            }

            //更新订单时间
//            $data1 = [
//                'start_time' => $start_time,
//                'end_time' => $end_time,
//                'carnum' => $car_num,
//                'order_id' => $order_id,
//                'goods_id' => $cid,
//                'sku_id' => $sku_id,
//                'uniacid' => $_W["uniacid"],
//            ];
//            $order_time = pdo_insert("yzzc_sun_ordertime", $data1);
//            if (!$order_time){
//                pdo_fetchall('ROLLBACK');//事务回滚
//                $this->return_msg(-1,'','预订失败');
//            }

            if($data['shuttle_id'] > 0){
                $branch_info = pdo_get("yzzc_sun_branch", array("id" => $data['start_shop']));
                $shuttle_data = [
                    'type' =>$branch_info['type'],
                    'branch_id' => $branch_info['id'],
                    'uniacid' => $_W['uniacid'],
                    'order_id' => $order_id,
                    'total' => $data['prepay_money'],
                    'amount' => $data['shuttle_commission'],
                    'shuttle_id' => $data['shuttle_id'],
                    'uid' => 0,
                    'createtime' => time(),
                ];
                if ($is_give_car == 1){
                    $shuttle_data['order_status'] = 1;
                }
                $shuttle_add = pdo_insert('yzzc_sun_shuttle_income',$shuttle_data);
                if (!$shuttle_add){
                    pdo_fetchall('ROLLBACK');//事务回滚
                    $this->return_msg(-1,'','创建订单收益失败');
                }
            }

            $branch = pdo_get("yzzc_sun_branch", ["uniacid" => $_W["uniacid"], "id" => $start_shop]);
            //创建收益
//            $platform_fee = round($data['prepay_money'] * ($branch['platform_fee'] / 100),2);

            $income = [
                'branch_id' => $branch['id'],
                'uniacid' => $branch['uniacid'],
                'order_id' => $order_id,
                'total' => $data['prepay_money'],
                'createtime' => time(),
            ];

            if ($store_income){
                $income['amount'] = $store_income['branch_cost'];
                $income['store_cost'] = $store_income['amount'];
                $income['store_id'] = $store_income['store_id'];
            }else{
                $income['amount'] = $data['prepay_money'];
                $income['store_cost'] = 0;
                $income['store_id'] = 0;
            }

            if ($store_income){
                //创建个人车主收益
                $store_income['order_id'] = $order_id;
                $store_income_result  = pdo_insert('yzzc_sun_store_income',$store_income);
                if (!$store_income_result){
                    pdo_fetchall('ROLLBACK');//事务回滚
                    $this->return_msg(-1,'','创建订单收益失败');
                }
            }

            if ($is_give_car){
                //交车
                $shuttle_data = [
                    'uniacid' => $_W['uniacid'],
                    'order_id' => $order_id,
                    'shuttle_id' => $data['shuttle_id'],
                    'delivery_start_time' => $data['start_time'],
                    'createtime' => time(),
                ];
                $shuttle_add = pdo_insert('yzzc_sun_shuttle_delivery',$shuttle_data);
                if (!$shuttle_add){
                    pdo_fetchall('ROLLBACK');//事务回滚
                    $this->return_msg(-1, [],'交车失败');
                }
            }

            $branch_income = pdo_insert('yzzc_sun_branch_income',$income);
            if (!$branch_income){
                pdo_fetchall('ROLLBACK');//事务回滚
                $this->return_msg(-1,'','创建订单收益失败');
            }
            //创建分销收益
            include_once IA_ROOT . "/addons/" . $_W["current_module"]["name"] . "/inc/func/distribution.php";
            $distribution = new Distribution();
            $distribution->order_id = $order_id;
            $distribution->money = $data["total_money"];
            $distribution->usertype = 1;
            $distribution->userid = 0;
            $distribution->parent_id = $uid;
            $distribution->ordertype = 1;
            $distribution->computecommission();
            pdo_fetchall('COMMIT');//事务提交
            $this->return_msg(1,$order_id,'预订成功');
        }catch (Exception $exception){
            pdo_fetchall('ROLLBACK');//事务回滚
            $this->return_msg(-1,'','预订失败');
        }
    }
    /**
     * @return void
     * 重新提交
     */
    public function doPageAgentUploadCar(){
        global $_W,$_GPC;
        if (!isset($_GPC['uid']) || !isset($_GPC['branch_id']) || !isset($_GPC['car_id'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }
        $goods_id = $_GPC['car_id'];
        $store = pdo_get('yzzc_sun_store',['uniacid'=>$_W['uniacid'],'store_id'=>$_GPC['store_id'],'uid'=>$_GPC['uid']]);
        if ($store['status'] !=1){
            $this->return_msg(-1, [], '入驻审核未通过');
        }

        if ($store['is_disable'] == 0){
            $this->return_msg(-1, [], '您已经被禁用，请联系管理员');
        }

        $goods_info =  pdo_get('yzzc_sun_goods',['uniacid'=>$_W['uniacid'],'id'=>$goods_id,'sid' => $_GPC['branch_id']]);
        if (!$goods_info){
            $this->return_msg(-1, [], '车辆不存在');
        }

        if ($goods_info['audit_status'] == 1){
            $this->return_msg(-1, [], '车辆已经通过审核，不能重新提交');
        }

        $branch_info = pdo_get('yzzc_sun_branch',['uniacid'=>$_W['uniacid'],'id'=>$_GPC['branch_id']]);
        if (!$branch_info){
            $this->return_msg(-1, [], '入驻审核未通过');
        }

        $spec = $_GPC['spec'] ?? '';
        if (!$spec){
            $this->return_msg(-1, [], '车辆详细信息必填');
        }

        $spec = json_decode(html_entity_decode($spec),true);
        $data = [
//            'uid' => $_GPC['uid'],
            'store_id' => $branch_info['store_id'],
            'sid' => $branch_info['id'],
            'store_name' => $branch_info['name'],
            'source_type' => $branch_info['type'],
            'uniacid' => $_W['uniacid'],
            'name' => trim($_GPC['car_name']),
            'structure' => trim($_GPC['structure']),
            'grarbox' => trim($_GPC['grarbox']),
            'num' => trim($_GPC['num']),
            'brand_id' => trim($_GPC['brand_id']),
            'pic' => trim($_GPC['pic']),
            'money' => trim($_GPC['money']),
            'audit_status' => 0,
            'createtime' => time()
        ];

        $result = pdo_update('yzzc_sun_goods',$data,['uniacid'=>$_W['uniacid'],'id'=>$goods_id,'sid' => $_GPC['branch_id']]);
        $delete_sku = pdo_delete('yzzc_sun_goods_sku',['goods_id'=>$goods_id]);
        if ($result && $delete_sku){
            foreach ($spec as $key => $value) {
                $sku = [
                    'carnum' => $value['car_num'],
                    'colour' => $value['car_color'],
                    'displacement' => $value['displacement'],
                    'goods_id' => $goods_id
                ];
                unset($data['audit_status']);
                $sku = array_merge($data,$sku);
                pdo_insert('yzzc_sun_goods_sku', $sku);
            }
            $this->return_msg(1, [], '提交成功，等待审核');
        }
        $this->return_msg(-1, [], '提交失败，请联系管理员');

    }
    /**
     * @return void
     * 新增库存
     */
    public function doPageAddCarSku(){
        global $_W,$_GPC;
        if (!isset($_GPC['car_id']) || !isset($_GPC['branch_id'])){
            $this->return_msg(-1, [], '会员ID不能为空');
        }

        $goods_id = $_GPC['car_id'];

        $store = pdo_get('yzzc_sun_store',['uniacid'=>$_W['uniacid'],'store_id'=>$_GPC['store_id'],'uid'=>$_GPC['uid']]);
        if ($store['status'] !=1){
            $this->return_msg(-1, [], '入驻审核未通过');
        }

        if ($store['is_disable'] == 0){
            $this->return_msg(-1, [], '您已经被禁用，请联系管理员');
        }

        $branch_info = pdo_get('yzzc_sun_branch',['uniacid'=>$_W['uniacid'],'id'=>$_GPC['branch_id']]);
        if (!$branch_info){
            $this->return_msg(-1, [], '入驻审核未通过');
        }
        $spec = $_GPC['spec'] ?? '';
        if (!$spec){
            $this->return_msg(-1, [], '车辆详细信息必填');
        }
        $goods_info =  pdo_get('yzzc_sun_goods',['uniacid'=>$_W['uniacid'],'id'=>$goods_id,'sid' => $_GPC['branch_id']]);
        if (!$goods_info){
            $this->return_msg(-1, [], '车辆不存在');
        }
        if ($goods_info['audit_status'] != 1){
            $this->return_msg(-1, [], '车辆未通过审核');
        }

        $spec = json_decode(html_entity_decode($spec),true);
        $data = [
            'store_id' => $goods_info['store_id'],
            'sid' => $goods_info['sid'],
            'store_name' => $goods_info['name'],
            'source_type' => $goods_info['type'],
            'uniacid' => $_W['uniacid'],
            'name' => $goods_info['name'],
            'structure' => $goods_info['structure'],
            'grarbox' => $goods_info['grarbox'],
            'num' => $goods_info['num'],
            'brand_id' => $goods_info['brand_id'],
            'pic' => $goods_info['pic'],
            'money' => $goods_info['money'],
            'createtime' => time()
        ];

        foreach ($spec as $key => $value) {
            $sku = [
                'carnum' => $value['car_num'],
                'colour' => $value['car_color'],
                'displacement' => $value['displacement'],
                'goods_id' => $goods_id
            ];
            unset($data['audit_status']);
            $sku = array_merge($data,$sku);
            pdo_insert('yzzc_sun_goods_sku', $sku);
        }
        $this->return_msg(1, [], '添加成功');
    }
    /**
     * @return void
     * 车辆详情
     */
    public function doPageStoreCarDetail(){
        global $_W,$_GPC;
        if (!isset($_GPC['branch_id']) || !isset($_GPC['id'])){
            $this->return_msg(-1, [], '商家ID不能为空');
        }

        $store = pdo_get('yzzc_sun_store',['uniacid'=>$_W['uniacid'],'store_id'=>$_GPC['branch_id'],'uid'=>$_GPC['uid']]);

        if (!$store){
            $this->return_msg(-1, [], '个人车主身份不存在');
        }
        if ($store['is_disable'] !=1 ){
            $this->return_msg(-1, [], '您已经被禁用');
        }
//        $branch_info = pdo_get('yzzc_sun_branch',['uniacid'=>$_W['uniacid'],'id'=>$_GPC['branch_id']]);
//        if (!$branch_info){
//            $this->return_msg(-1, [], '入驻审核未通过');
//        }

        $goods_info = pdo_get('yzzc_sun_goods',['id' =>$_GPC['id'],'uniacid'=>$_W['uniacid'],'is_del'=>0]);
        if (!$goods_info){
            $this->return_msg(-1, [], '车辆不存在');
        }
        $brand_name = pdo_get('yzzc_sun_carbrand',['id' =>$goods_info['brand_id'],'uniacid'=>$_W['uniacid']]);
        $goods_info['brand_name'] =$brand_name['name'];

        $cartype = pdo_get('yzzc_sun_cartype',['id' =>$goods_info['cartype'],'uniacid'=>$_W['uniacid']]);
        $goods_info['cartypename'] =$cartype['name'];

        $sku = pdo_fetchall('select id,carnum as car_num,colour as car_color,structure,displacement from '.tablename('yzzc_sun_goods_sku').' where goods_id='.$_GPC['id'].' and is_del = 0');
        $goods_info['sku'] = $sku;

        $this->return_msg(1, $goods_info, '操作成功');
    }



    /**
     * @return void
     * 操作成功
     */
    public function doPageDeleteGoodsSku(){
        global $_GPC, $_W;
        $sku_id = $_GPC['sku_id'];
        $goods_id = $_GPC['car_id'];
        $sku_info = pdo_get('yzzc_sun_goods_sku',['id'=>$sku_id,'goods_id'=>$goods_id,'is_del'=>0]);
        if (!$sku_info){
            $this->return_msg(-1, [], '库存车辆不存在');
        }
        if ($sku_info['status'] == 2){
            $this->return_msg(-1, [], '库存车辆已出租，不能删除');
        }
        $goods = pdo_count('yzzc_sun_goods_sku',['goods_id'=>$goods_id,'is_del'=>0]);

        if ($goods <=1){
            $this->return_msg(-1, [], '一个车型至少保留一个规格');
        }
        $result = pdo_update('yzzc_sun_goods_sku',['is_del'=>time()],['id'=>$sku_id,'goods_id'=>$goods_id,'is_del'=>0]);
        if (!$result){
            $this->return_msg(-1, [], '操作失败');
        }
        $this->return_msg(1, [], '操作成功');
    }

    /**
     * @return void
     * 车辆上架
     */
    public function doPageCarShelves(){
        global $_GPC;
        $goods_id = $_GPC['car_id'];
        $status = $_GPC['status'];
//        $money = $_GPC['money'];
//        if (!$money && $status == 1){
//            $this->return_msg(-1, [], '请输入车辆实际出租价格');
//        }
        $sku_info = pdo_get('yzzc_sun_goods',['id'=>$goods_id,'is_del'=>0]);
        if (!$sku_info){
            $this->return_msg(-1, [], '车辆不存在');
        }

        if ($sku_info['audit_status'] != 1){
            $this->return_msg(-1, [], '车辆审核未通过');
        }

        if ($status!=1 && $status!=3){
            $this->return_msg(-1, [], '上下架状态不正确');
        }

        if ($sku_info['status'] == $status){
            $this->return_msg(-1, [], '已经完成上架或者下架 无需重复操作');
        }

        $result = pdo_update('yzzc_sun_goods',['status'=>$status,'updatetime'=>time()],['id'=>$goods_id,'is_del'=>0]);
        if (!$result){
            $this->return_msg(-1, [], '操作失败，请联系管理员');
        }
        $this->return_msg(1, [], '操作成功');
    }
   /********************************商户会员********************************/
    /**
     * @return void
     * 商家套餐列表
     */
    public function doPageGetStoreMember(){
        global $_W;
        $store_config = pdo_getall('yzzc_sun_store_member',['uniacid'=>$_W['uniacid'],'status'=>1],[],'','month asc');
        $this->return_msg(1, $store_config, '获取成功');
    }

    /**
     * @return void
     * 开通会员
     */
    public function doPageCreateStoreMember(){
        global $_W,$_GPC;
        if (empty($_GPC['store_id']) || !$_GPC['uid']){
            $this->return_msg(-1,[],'商户ID必传');
        }
        if (empty($_GPC['id'])){
            $this->return_msg(-1,[],'会员套餐ID必传');
        }

        $member = pdo_get('yzzc_sun_store_member',['uniacid'=>$_W['uniacid'],'id'=>$_GPC['id']]);
        if (!$member || $member['status'] != 1){
            $this->return_msg(-1,[],'会员套餐下架');
        }

        $user = pdo_get('yzzc_sun_user',['uniacid'=>$_W['uniacid'],'id'=>$_GPC['uid']]);
        if (!$user){
            $this->return_msg(-1,[],'会员未注册');
        }

        $store = pdo_get('yzzc_sun_store',['uniacid'=>$_W['uniacid'],'store_id'=>$_GPC['store_id']]);
        $data = [
            'uid' => $_GPC['uid'],
            'store_id' => $_GPC['store_id'],
            'order_no' => $this->getOrderNo(),
            'uniacid' => $_W['uniacid'],
            'name' => $store['name'],
            'mobile' => $store['mobile'],
            'amount' => $member['money'],
            'createtime' => time(),
            'member_month' => $member['month'],
            'member_id' => $member['id'],
            'openid' => $user['openid'],
        ];
        pdo_insert('yzzc_sun_store_order',$data);
        $order_id = pdo_insertid();
        if ($order_id){
            $out_trade_no = rand(10000, 99999) . time() . rand(10000, 99999) . $order_id;
            pdo_update("yzzc_sun_store_order", array("out_trade_no" => $out_trade_no), array("order_id" => $order_id));

            $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
            $appid = $appData["appid"];
            $mch_id = $appData["mchid"];
            $key = $appData["wxkey"];
            $openid = $user["openid"];
            $total_fee = $data["amount"] * 100;

            $body = "开通商家会员";
            $notify_url = $_W["siteroot"] . "addons/yzzc_sun/notify.php";

            //3 支付商家入驻订单
            $attach = $_W["uniacid"] . "@@@3@@@" . $order_id;
            include_once "wxpay.php";
            $wxpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $attach, $notify_url);

            $ret = $wxpay->pay();
            $ret['order_id'] = $order_id;
            $this->return_msg(1, $ret);
        }else{
            $this->return_msg(-1,[],'创建订单失败');
        }
    }

    /**
     * @return void
     * 查询订单状态
     */
    public function doPageGetOrderStatus(){
        global $_W,$_GPC;
        $user = pdo_get('yzzc_sun_store_order',['uniacid'=>$_W['uniacid'],'order_id'=>$_GPC['order_id']],'pay_status');
        $this->return_msg(1, $user);
    }


    /**
     * @return void
     * 省市级
     */
    public function doPageGetCityTree(){
        $city = pdo_fetchall('select id,name,code,name,fullname,lat,lng,pcode as pid FROM '.tablename('yzzc_sun_city') . ' where id > 0');
        $city = $this->buildTree($city,0);
        $this->return_msg(1,$city);
    }

    /*****************************************************交车员***********************************************/
    /**
     * @return void
     * 销售详情
     */
    public function doPageShuttleDetail(){
        global $_GPC, $_W;
        $uid = $_GPC['uid'];
        if (!$uid){
            $this->return_msg(-1,[],'参数错误');
        }

//        $this->checkStore($uid);
        $branch_admin = pdo_get("yzzc_sun_shuttle", array("uid" => $_GPC["uid"]),['id','name','balance','branch_ids']);
        if (!$branch_admin){
            $this->return_msg(-1,[],'交还车身份不存在');
        }
        $data["admin_info"] = $branch_admin;
        $branch_info_ids = pdo_getall("yzzc_sun_branch", array("id in" => explode(',',$branch_admin["branch_ids"]),'status'=>1),['id','name']);
        $data['shop_info'] = $branch_info_ids;

        //非平台门店。统计收益
        $total_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_shuttle_income") . "where uniacid = " . $_W["uniacid"] ." and shuttle_id = {$branch_admin['id']}");
        $wait_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_shuttle_income") . "where uniacid = " . $_W["uniacid"] . " and status = 0 and order_status = 2 and shuttle_id = {$branch_admin['id']}");
        $finish_amount = pdo_fetch("SELECT SUM(amount) as money FROM " . tablename("yzzc_sun_shuttle_income") . "where uniacid = " . $_W["uniacid"] . " and status = 1 and order_status = 2 and shuttle_id = {$branch_admin['id']}");
        $data['branch_income'] = [
            'total_amount' => $total_amount['money'] ?? 0.00,
            'wait_amount' => $wait_amount['money'] ?? 0.00,
            'finish_amount' => $finish_amount['money'] ?? 0.00,
            'balance' => $branch_admin['balance'] ?? 0.00,
        ];

        //待处理
        $wait_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop in({$branch_admin['branch_ids']}) and status = 2");
        //进行中
        $processing_order = pdo_fetchcolumn("SELECT COUNT(id) FROM " . tablename("yzzc_sun_order") . "where uniacid = " . $_W["uniacid"] . " and start_shop in({$branch_admin['branch_ids']})  and status = 3");
        $data['order'] = [
            'wait_order' => $wait_order ?? 0,
            'processing_order' => $processing_order ?? 0,
        ];

//        $car_lists = pdo_getall('yzzc_sun_order',['start_shop in'=>explode(',',$branch_admin["branch_ids"]),'display' => 1,'shuttle_id'=>0,'status'=>2,'uniacid'=>$_W["uniacid"]],['id','source_type','sku_id','is_inner','cid','start_time','end_time','start_shop','end_shop','day','createtime','shuttle_commission','total_money','carnum','car_name','user_address','user_lat','user_lng']);
//        foreach ($car_lists as $key => $val){
//            //销量
//            if ($val['is_inner'] == 1){
//                $car = pdo_get('yzzc_sun_goods_sku',['goods_id'=>$val['cid'],'id'=>$val['sku_id'],'is_del'=>0],['name','carnum','colour','structure','grarbox','num','pic']);
//            }else{
//                $car = [
//                    'carnum' => $val['carnum'],
//                    'name' => $val['car_name']
//                ];
//            }
//            $car_lists[$key]['carinfo'] = $car;
//            $shop = pdo_get('yzzc_sun_branch',['id'=>$val['start_shop']],['name','province','city','area','lng','lat','shop_tel','pic','ranges','address']);
//            $car_lists[$key]['shopinfo'] = $shop;
//        }
//        $data['order_list'] = $car_lists;
        $data['order_list'] = [];
        $this->return_msg(1, $data);
    }

    /**
     * @return void
     * 交还车接单
     */
    public function doPageShuttleTakeOrders(){
        global $_GPC, $_W;
        if (!isset($_GPC['id']) || !isset($_GPC['uid'])){
            $this->return_msg(-1,[],'参数错误');
        }
        $uid = $_GPC['uid'];
        $id = $_GPC['id'];
//        $shuttle_id = $_GPC['shuttle_id'];
        $order_info  = pdo_get("yzzc_sun_order", array("id" => $id));
        if (!$order_info){
            $this->return_msg(-1,[],'订单不存在');
        }

        $shuttle_id = $this->isShuttle($uid);

        if ($order_info['shuttle_id'] > 0){
            $this->return_msg(-1,[],'该订单已被接单');
        }

        if (pdo_get('yzzc_sun_shuttle_income',['uid'=>$uid,'order_id'=>$order_info['id']])){
            $this->return_msg(-1,[],'已经接单，请勿重复操作');
        }
        $shuttle = pdo_get('yzzc_sun_shuttle_income',['id'=>$shuttle_id]);
        $order_update = pdo_update('yzzc_sun_order',['shuttle_id'=>$shuttle_id,'shuttle_name' => $shuttle['name']],['id'=>$order_info['id']]);
        if ($order_update){
            $this->return_msg(1, [],'接单成功');
        }
        $this->return_msg(-1, [],'接单失败');
//        $branch_info = pdo_get("yzzc_sun_branch", array("id" => $order_info['start_shop']));
//
//        $data = [
//            'type' =>$branch_info['type'],
//            'branch_id' => $branch_info['id'],
//            'uniacid' => $_W['uniacid'],
//            'order_id' => $id,
//            'total' => $order_info['prepay_money'],
//            'amount' => $order_info['shuttle_commission'],
//            'shuttle_id' => $shuttle_id,
//            'uid' => $uid,
//            'createtime' => time(),
//        ];
//        $shuttle_add = pdo_insert('yzzc_sun_shuttle_income',$data);
//        $order_update = pdo_update('yzzc_sun_order',['shuttle_id'=>$shuttle_id],['id'=>$order_info['id']]);
//        if ($shuttle_add && $order_update){
//            $this->return_msg(1, [],'接单成功');
//        }
//        $this->return_msg(-1, [],'接单失败');
    }

    /**
     * @param $uid
     * @return mixed
     * 检测交车员
     */
    private function isShuttle($uid)
    {
        $shuttle = pdo_get('yzzc_sun_shuttle',['uid'=>$uid]);
        if (!$shuttle){
            $this->return_msg(-1,[],'交车员身份不存在');
        }
        return $shuttle['id'];
    }

    /**
     * @param $uid
     * @return mixed
     * 检测销售员
     */
    private function isDistribution($uid)
    {
        $shuttle = pdo_get('yzzc_sun_distribution_promoter',['uid'=>$uid]);
        if (!$shuttle){
            $this->return_msg(-1,[],'销售身份不存在');
        }

        if ($shuttle['status'] != 1){
            $this->return_msg(-1,[],'身份状态异常，请联系管理员');
        }
        return $shuttle['id'];
    }
    /**
     * @return void
     * 交换车员上传合同
     */
    public function doPageUpdateContract()
    {
        global $_GPC, $_W;
        if (!isset($_GPC['order_id']) || !isset($_GPC['uid']) || !isset($_GPC['contract'])){
            $this->return_msg(-1,[],'参数错误');
        }
        $contract = $_GPC['contract'];
        $order_id = $_GPC['order_id'];
        $shuttle_id = $this->isShuttle($_GPC['uid']);

        $order = pdo_get('yzzc_sun_order',['id'=>$order_id]);
        if (!$order){
            $this->return_msg(-1,[],'订单不存在');
        }

        $res = pdo_update('yzzc_sun_order',['contract' => $contract,'contract_shuttle_id' =>$shuttle_id ],['id' => $order_id]);
        if ($res){
            $this->return_msg(1,[],'合同上传成功');
        }else{
            $this->return_msg(-1,[],'合同上传失败');
        }
    }
    /**
     * @return void
     * 列表信息
     */
    public function doPageShuttleOrderLists(){

        global $_GPC, $_W;
        if (!isset($_GPC['uid'])){
            $this->return_msg(-1,[],'参数错误');
        }
        $uid = $_GPC['uid'];
        $shuttle_id = $this->isShuttle($uid);

        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;
        $start = ($page - 1) * $length;
        $status = $_GPC['status'] ?? 0;

//        if ($status == 0){
//            $where = 'i.uniacid ='.$_W['uniacid'] . ' and i.order_status = '.$status.' and o.shuttle_id='.$shuttle_id;
//        }else{
//            $branch_ids = pdo_fetchcolumn('select branch_ids from '.tablename('yzzc_sun_shuttle').' where id ='.$shuttle_id);
//            $where = 'i.uniacid ='.$_W['uniacid'] . ' and i.order_status = '.$status.' and i.branch_id in('.$branch_ids.')';
//        }
//
//        $sql = 'select i.id,i.amount,i.order_status,o.source_type,o.is_inner,o.fdd_status,o.fdd_task_id,o.contract,i.order_id,o.sku_id,o.cid,o.start_shop,o.start_time,o.end_time,o.day,o.car_name,o.carnum,o.shuttle_commission,o.total_money from '.tablename('yzzc_sun_shuttle_income').' i left join '.tablename('yzzc_sun_order').' o on i.order_id=o.id where '.$where .' order by i.id desc limit '.$start.','.$length;


        $branch_ids = pdo_fetchcolumn('select branch_ids from '.tablename('yzzc_sun_shuttle').' where id ='.$shuttle_id);
        $where = 'uniacid ='.$_W['uniacid']. ' and start_shop in('.$branch_ids.')';
        if ($status == 0){
            $where.= ' and status = 2 ';
        }else{
            $where.= ' and status = 3 ';
        }

        $sql = 'select id,id as order_id,cid,sku_id,is_inner,car_name,carnum,start_shop,status,money,total_money,start_time,end_time,shuttle_commission from '.tablename('yzzc_sun_order').' where '.$where .' order by id desc limit '.$start.','.$length;

        $order_list = pdo_fetchall($sql);
        if ($order_list){
            foreach ($order_list as $key => $val){
                //销量
                $car = pdo_get('yzzc_sun_goods_sku',['goods_id'=>$val['cid'],'id'=>$val['sku_id'],'is_del'=>0],['name','carnum','colour','structure','grarbox','num','pic','displacement']);

                if ($val['is_inner'] == 2 && $val['sku_id'] <= 0){
                    //外调
                    $car = [
                        'name' => $val['car_name'],
                        'carnum' => $val['carnum'],
                    ];
                }

                $order_list[$key]['carinfo'] = $car;
                $shop = pdo_get('yzzc_sun_branch',['id'=>$val['start_shop']],['name','province','city','area','lng','lat','shop_tel','pic','ranges','address']);
                $order_list[$key]['shopinfo'] = $shop;
            }
        }
        $this->return_msg(1,$order_list,'操作成功');
    }

    /**
     * @return void
     * 交还车基础信息
     */
    public function doPageShuttleDeliveredInfo(){
        global $_GPC, $_W;
        if (!isset($_GPC['shuttle_income_id'])){
            $this->return_msg(-1,[],'参数错误');
        }
        $uid = $_GPC['uid'];
        $shuttle_income_id = $_GPC['shuttle_income_id'];
        if (!pdo_get('yzzc_sun_shuttle',['uid'=>$uid])){
            $this->return_msg(-1, [],'身份不存在');
        }
        $where = 'i.uniacid ='.$_W['uniacid'] . ' and i.id ='.$shuttle_income_id;

        $sql = 'select i.id,i.amount,i.order_status,i.order_id,o.sku_id,o.cid,o.start_shop,o.start_time,o.end_time,o.day,o.shuttle_commission from '.tablename('yzzc_sun_shuttle_income').' i left join '.tablename('yzzc_sun_order').' o on i.order_id=o.id where '.$where;
        $order_list = pdo_fetch($sql);

        if ($order_list){
            $car = pdo_get('yzzc_sun_goods_sku',['goods_id'=>$order_list['cid'],'id'=>$order_list['sku_id'],'is_del'=>0],['name','carnum','colour','structure','grarbox','num','pic']);
            $order_list['carinfo'] = $car;
            $shop = pdo_get('yzzc_sun_branch',['id'=>$order_list['start_shop']],['name','province','city','area','lng','lat','shop_tel','pic','ranges','address']);
            $order_list['shopinfo'] = $shop;
        }
        $this->return_msg(1,$order_list ?? [],'操作成功');
    }

    /**
     * @return void
     * 交车员还车
     */
    public function doPageShuttleDelivered(){
        global $_GPC, $_W;
        if (!isset($_GPC['uid']) || !isset($_GPC['order_id']) || !isset($_GPC['type'])){
            $this->return_msg(-1,[],'参数错误');
        }
        $order_id = $_GPC['order_id'];
        $uid = $_GPC['uid'];

        $shuttle_id = $this->isShuttle($uid);

        $shuttle = pdo_get('yzzc_sun_shuttle',['uid'=>$uid]);
        $type = $_GPC['type'];
        $order_info  = pdo_get("yzzc_sun_order", array("id" => $order_id));
        if (!$order_info){
            $this->return_msg(-1,[],'订单不存在');
        }
        if ($order_info['status'] == 0){
            $this->return_msg(-1,[],'订单已完成');
        }


        try {
            pdo_fetchall('START TRANSACTION');//启动一个新事务
            if ($type == 1){
                //交车
                $data = [
                    'uniacid' => $_W['uniacid'],
                    'order_id' => $order_id,
                    'shuttle_id' => $shuttle_id,
                    //'uid' => $uid,
//                    'km_start' => trim($_GPC['km']),
                    'delivery_start_time' => strtotime(trim($_GPC['time'])),
                    'delivery_start_pic' => trim($_GPC['pic']),
                    'delivery_start_meter' => trim($_GPC['meter']),
//                    'petrol_start' => trim($_GPC['petrol']),
//                    'deposit' => $_GPC['deposit'],
//                    'security' => $_GPC['security'],
//                    'give_car_cost' => $_GPC['give_car_cost'],
                    'createtime' => time(),
                ];


                $shuttle_add = pdo_insert('yzzc_sun_shuttle_delivery',$data);
                $order_update = pdo_update('yzzc_sun_order',['status'=>3,'usetime'=>time(),'shuttle_name' => $shuttle['name'],'shuttle_id'=>$shuttle_id],['id'=>$order_info['id']]);
//                $shuttle_update = pdo_update('yzzc_sun_shuttle_income',['order_status'=>1],['order_id'=>$order_info['id'],'shuttle_id'=>$shuttle_id]);
                if ($shuttle_add && $order_update){
                    pdo_fetchall('COMMIT');//事务提交
                    $this->return_msg(1, [],'交车成功');
                }
                pdo_fetchall('ROLLBACK');//事务回滚
                $this->return_msg(-1, [],'交车失败');
            }
            elseif ($type == 2){
                //还车
                $data = [
                    'delivery_end_time' => strtotime(trim($_GPC['time'])),
                    'delivery_end_pic' => trim($_GPC['pic']),
                    'delivery_end_meter' => trim($_GPC['meter']),
                ];

                //计算天数
                if ($data['delivery_end_time'] <= $order_info['start_time']){
                    $this->return_msg(-1,'','还车时间不能小于租车时间');
                }
                $day = $this->day($data['delivery_end_time'],$order_info['start_time']);

                $order_total_money =  number_format($order_info['money'] * $day,2,'.','');

                if ($order_total_money > $order_info['total_money']){
                    //还车金额大于租车金额
                    $store_update = [];

                    if ($order_info['store_id'] > 0){
                        //更新个人车主收益
                        $store_info = pdo_get('yzzc_sun_store',['store_id' => $order_info['store_id']]);

                        //创建收益
                        $platform_fee = round($order_total_money * ($store_info['platform_fee'] / 100),2);
                        $store_update = [
                            'total' => $order_total_money,
                            'branch_cost' => $platform_fee,
                            'amount' => $order_total_money - $platform_fee,
                        ];

                        $store_income_result  = pdo_update('yzzc_sun_store_income',$store_update,['store_id'=>$order_info['store_id'],'order_id'=>$order_info['id']]);
                        if (!$store_income_result){
                            pdo_fetchall('ROLLBACK');//事务回滚
                            $this->return_msg(-1,'','更新个人车主佣金失败');
                        }
                    }

                    //更新门店
                    $branch_data = [
                        'total' => $order_total_money,
                        'store_cost' => 0,
                        'amount' => $order_total_money,
                    ];
                    if(isset($store_update['branch_cost'])){
                        $branch_data['store_cost'] = $store_update['amount'];
                        $branch_data['amount'] = $store_update['branch_cost'];
                    }
                    $branch_income_result  = pdo_update('yzzc_sun_branch_income',$branch_data,['branch_id'=>$order_info['start_shop'],'order_id'=>$order_info['id']]);
                    if (!$branch_income_result){
                        pdo_fetchall('ROLLBACK');//事务回滚
                        $this->return_msg(-1,'','更新门店佣金失败');
                    }

                    //更新销售
                    include_once IA_ROOT . "/addons/" . $_W["current_module"]["name"] . "/inc/func/distribution.php";
                    $distribution = new Distribution();
                    $distribution->order_id = $order_id;
                    $distribution->money = $order_total_money;
                    $distribution->usertype = 1;
                    $distribution->userid = 0;
                    $distribution->parent_id = $order_info['distribution_id'];
                    $distribution->ordertype = 1;
                    $distribution->computecommission();
                }

                $is_onsite = $_GPC['is_onsite'];
//                if ($is_onsite == 1){
//                    //上门取车，增加取车佣金
//                    $delivery_add = [
//                        'delivery_type' => 2,
//                        'branch_id' => $order_info['start_shop'],
//                        'shuttle_id' => $shuttle_id,
//                        'uid' => 0,
//                        'uniacid' => $_W['uniacid'],
//                        'order_id' => $order_id,
//                        'total' => $order_total_money,
//                        'amount' => $order_info['shuttle_commission'],
//                        'order_status' => 2,
//                        'createtime' => time()
//                    ];
//                    $delivery_add_result = pdo_insert('yzzc_sun_shuttle_income',$delivery_add);
//                    if (!$delivery_add_result){
//                        pdo_fetchall('ROLLBACK');//事务回滚
//                        $this->return_msg(-1,'','更新还车员佣金失败');
//                    }
//                }


                $delivery_info = pdo_get('yzzc_sun_shuttle_delivery',['order_id'=>$order_id]);
                if (!$delivery_info){
                    $this->return_msg(-1, [],'尚未交车');
                }

//                //创建商家结算费用
//                $branch_income = pdo_get("yzzc_sun_branch_income", ["uniacid" => $_W["uniacid"], "branch_id" => $order_info["start_shop"],'order_id'=>$order_info['id']]);
//                if ($branch_income){
//                    //存在收益。直接结算
//                    $income_result = pdo_update('yzzc_sun_branch_income',['status' => 1,'income_time' => time()],['id'=>$branch_income['id']]);
//                    if (!$income_result){
//                        pdo_fetchall('ROLLBACK');//事务提交
//                        $this->return_msg(-1, [],'结算商家收益失败');
//                    }
//                }

                $goods = pdo_get('yzzc_sun_goods',['id'=>$order_info['cid']]);
                if ($goods['status'] != 1){
                    pdo_update('yzzc_sun_goods',['status'=>1],['id'=>$order_info['cid']]);
                }

//                pdo_update('yzzc_sun_ordertime',['end_time' => $data['delivery_end_time'],'status'=>0],['sku_id'=>$order_info['sku_id'],'order_id'=>$order_info['id']]);
//                $reclaim_shuttle_name = pdo_fetchcolumn('select name from '.tablename('yzzc_sun_shuttle').' where id='.$shuttle_id);
                $order_update_data = [
                    'status'=>0,
                    'return_time'=>time(),
                    'end_time' => $data['delivery_end_time'],
                    'reclaim_shuttle_id' => $shuttle_id,
                    'total_money' => $order_total_money,
                    'prepay_money' => $order_total_money,
                    'day' => $day,
                    'is_onsite' => $is_onsite,
                    'reclaim_shuttle_name' => $shuttle['name']
                ];

                $delivery_update = pdo_update('yzzc_sun_shuttle_delivery',$data,['order_id'=>$order_id]);
                $order_update = pdo_update('yzzc_sun_order',$order_update_data,['id'=>$order_info['id']]);
//                $shuttle_update = pdo_update('yzzc_sun_shuttle_income',['order_status'=>2],['order_id'=>$order_info['id']]);
                if ($delivery_update && $order_update){
                    pdo_fetchall('COMMIT');//事务提交
                    $this->return_msg(1, [],'还车成功');
                }
                pdo_fetchall('ROLLBACK');//事务回滚
                $this->return_msg(-1, [],'还车失败');
            }else{
                $this->return_msg(-1, [],'类型状态错误');
            }
        }catch (Exception $exception){
            $this->return_msg(-1, [],'类型状态错误');
        }
    }

    /**
     * @return void
     * 销售确认尾款
     */
    public function doPageFinishPayment()
    {
        global $_GPC,$_W;
        $uid = $_GPC['uid'];
        $order_id = $_GPC['order_id'];
        if (!$uid || !$order_id){
            $this->return_msg(-1, [],'会员ID和订单ID必传');
        }

        $this->isDistribution($uid);

        $order = pdo_get('yzzc_sun_order',['id' => $order_id,'distribution_id' => $uid]);
        if (!$order){
            $this->return_msg(-1, [],'订单不存在');
        }

        if ($order['status'] != 0){
            $this->return_msg(-1, [],'订单状态未完成，不能更改状态');
        }

        try {
            pdo_fetchall('START TRANSACTION');//启动一个新事务

            $delivery_info = pdo_get('yzzc_sun_shuttle_delivery',['order_id'=>$order_id]);
            if (!$delivery_info){
                $this->return_msg(-1, [],'尚未交车');
            }

            //是否是个人车主车辆
            $store_income = [];
            if ($order['cid'] > 0){
                $goods = pdo_get('yzzc_sun_goods',['id' =>$order['cid']]);
                if (!$goods){
                    $this->return_msg(-1,'','车辆基础信息不存在');
                }

                if ($goods['store_id'] > 0){
                    //商家
                    $store_info = pdo_get('yzzc_sun_store',['store_id' => $goods['store_id']]);
                    if (!$store_info){
                        $this->return_msg(-1,'','个人车主信息不存在');
                    }
                    //创建收益
                    $platform_fee = round($order['prepay_money'] * ($store_info['platform_fee'] / 100),2);
                    $store_income = [
                        'type' => 3,
                        'branch_id' => 0,
                        'uniacid' => $store_info['uniacid'],
                        'order_id' => $order_id,
                        'total' => $order['prepay_money'],
                        'platform_fee' => $platform_fee,
                        'amount' => $order['prepay_money'] - $platform_fee,
                        'createtime' => time(),
                    ];
                    //创建个人车主收益
                    $store_income_result  = pdo_insert('yzzc_sun_branch_income',$store_income);
                    if (!$store_income_result){
                        pdo_fetchall('ROLLBACK');//事务回滚
                        $this->return_msg(-1,'','创建订单收益失败');
                    }
                }
            }

            $zlsz = pdo_get("yzzc_sun_order_set", ["uniacid" => $_W["uniacid"]], ["zlsz",'shuttle_type','shuttle_commission']);
            //计算交还车原收益
            $shuttle_commission = 0;
            if ($zlsz['shuttle_type'] == 1){
                //订单总额百分比
                $shuttle_commission =  round(($zlsz['shuttle_commission'] / 100) * $order['prepay_money'],2);
            }
            if ($zlsz['shuttle_type'] == 2){
                //订单总额固定值
                $shuttle_commission = $zlsz['shuttle_commission'];
            }

            $data['shuttle_commission'] = $shuttle_commission;

            $branch = pdo_get("yzzc_sun_branch", ["uniacid" => $_W["uniacid"], "id" => $order['start_shop']]);
            if ($branch['member_end_time'] < time()){
                //创建收益
                $platform_fee = round($order['prepay_money'] * ($branch['platform_fee'] / 100),2);
                $income = [
                    'type' => $branch['type'],
                    'branch_id' => $branch['id'],
                    'uniacid' => $branch['uniacid'],
                    'order_id' => $order_id,
                    'total' => $order['prepay_money'],
                    'platform_fee' => $platform_fee,
                    'amount' => $order['prepay_money'] - $platform_fee,
                    'createtime' => time(),
                ];
                $income_result = pdo_insert('yzzc_sun_branch_income',$income);
                if (!$income_result){
                    pdo_fetchall('ROLLBACK');//事务回滚
                    $this->return_msg(-1,'','创建订单收益失败');
                }
            }

            //创建分销收益
            include_once IA_ROOT . "/addons/" . $_W["current_module"]["name"] . "/inc/func/distribution.php";
            $distribution = new Distribution();
            $distribution->order_id = $order_id;
            $distribution->money = $data["total_money"];
            $distribution->usertype = 1;
            $distribution->userid = 0;
            $distribution->parent_id = $uid;
            $distribution->ordertype = 1;
            $distribution->computecommission();

            pdo_fetchall('COMMIT');//事务提交
            $this->return_msg(1,$order_id,'预订成功');

        }catch (Exception $exception){
            $this->return_msg(-1, [],'类型状态错误');
        }

    }


    /**
     * @return void、
     * 意见反馈
     */
    public function doPagefeedback()
    {
        global $_GPC,$_W;
        $uid = $_GPC['uid'];
        $title = $_GPC['title'];
        $content = $_GPC['content'];
        $phone = $_GPC['phone'];
        $name = $_GPC['name'];
        if (!$uid || !$title){
            $this->return_msg(-1, [],'参数缺少');
        }

        $data = [
            'uid' => $uid,
            'title' => $title,
            'uniacid' => $_W['uniacid'],
            'phone' => $phone,
            'name' => $name,
            'content' => $content,
            'createtime' => time()
        ];
        $res = pdo_insert('yzzc_sun_user_feedback',$data);
        if (!$res){
            $this->return_msg(-1, [],'提交失败，请联系管理员');
        }
        $this->return_msg(1, [],'提交成功');
    }

    /****************************发大大******************************/
    const HOST = 'https://uat-api.fadada.com/api/v5';

    const APPID = '80000490';
    const OPEN_CORP_ID = 'f8d0ede4f9174251a7df371d12b4d7e3';
    const APP_SECRET = '7XJ34X0IRU1THVKBKQCK9ZHBREKGS6PM';
    function commonHeader()
    {
        return [
            "X-FASC-App-Id"         => self::APPID,
            "X-FASC-Sign-Type"      => "HMAC-SHA256",
            "X-FASC-Timestamp"      => (int)(microtime(true) * 1000),
            "X-FASC-Nonce"          => uniqid("fdd"),
            "X-FASC-Grant-Type"     => "client_credential",
            "X-FASC-Api-SubVersion" => "5.1",
        ];
    }

    function headerHandle(array $params): array
    {
        $result = [];
        foreach ($params as $k => $v) {
            $result[] = $k . ": " . $v;
        }
        return $result;
    }
    function getFddAccessToken()
    {
        $response = $this->send('/service/get-access-token');
        return $response['data']['accessToken'];
    }
    /**
     * @param string $path
     * @param array $data
     * @param string $method
     * @return array|bool|float|int|mixed|stdClass|string|null
     * @throws Exception
     * 发送请求
     */
    function send(string $path, array $data = [], string $method = 'POST')
    {
        $headers =  $this->commonHeader();
        if ($data){
            $data = json_encode($data);
            $headers['X-FASC-AccessToken'] = $this->getFddAccessToken();
            $headers['bizContent'] = $data;
            unset($headers['X-FASC-Grant-Type']);
        }
        ksort($headers);
        $sortParam = urldecode(http_build_query($headers));
        $signText = strtolower(hash("sha256", $sortParam));
        $hash = hash_hmac("sha256", $headers['X-FASC-Timestamp'], self::APP_SECRET, true);
        $sign = hash_hmac("sha256", $signText, $hash);
        $headers['X-FASC-Sign']  = $sign;
        $headers['Content-type'] = "application/x-www-form-urlencoded";

        unset($headers['bizContent']);
        $postHeader = $this->headerHandle($headers);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::HOST . $path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $postHeader);
        curl_setopt($ch, CURLOPT_POST, $method === "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if($data){
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['bizContent' => $data]));
        }
        $res = curl_exec($ch);
        curl_close($ch);

        $res = json_decode($res, true);
        if ($res['code'] != 100000) {
            $this->return_msg(-1,[],$res['msg']);
        }

        return $res;
    }


    public function getSignTemplateDetail()
    {
        try {
            $res = $this->send('/sign-template/get-detail', [
                'signTemplateId' => '1702963836720153721',
            ]);
            return $res['data'];
        } catch (\Throwable $exception) {
            $this->return_msg(-1,[],$exception->getMessage());
        }
    }
    /**
     * 按模板id创建签署任务
     *
     * @return void
     */
    public function doPagecreateSignTaskByTemplateId()
    {
        //dd($this->getSignTemplateDetail());
        global $_GPC;
        $uid = $_GPC['uid'];
        $order_id = $_GPC['order_id'];
        if (!$uid || !$order_id){
            $this->return_msg(-1,[],'uid不能为空');
        }
        $user = pdo_get('yzzc_sun_user',['id'=>$uid]);
        $drive = pdo_get('yzzc_sun_user_drive',['uid'=>$uid]);
        if (!$user){
            $this->return_msg(-1,[],'会员不存在');
        }
        $order_info = pdo_get('yzzc_sun_order',['id'=>$order_id]);
        $sku_id = $order_info['sku_id'];
        $total_price = $order_info['total_money'];
        $start_time = $order_info['start_time'];
        $year = date('Y-m-d H:i:s',$start_time);
        $day_number = $order_info['day'];
        $sku_info = pdo_get('yzzc_sun_goods_sku',['id'=>$sku_id]);
        $templateId = '1702963836720153721';
        try {
            //创建
            $res = $this->send('/sign-task/create-with-template', [
                'initiator' => [
                    'idType' => 'corp',
                    'openId' => self::OPEN_CORP_ID
                ],
                'signTaskSubject' => "租车合同",
                'signTemplateId' => $templateId,
                'businessId' => '82aadab14727127e7bb61490da182581',
                'actors' => [
                    'Actor' => [
                        'actorId' => '承租方',
                        'actorType' => 'person',
                        'actorName' => $drive['name'],
                        'permissions' => [
                            "sign",
                        ],
                    ],
                ]
            ]);

            //填写
            $signFields = [
                ["docId"=>"40151231", "fieldId"=>"1615599847", "fieldName"=>"姓名", "fieldValue"=>$drive['name']],
                ["docId"=>"40151231", "fieldId"=>"8645263399", "fieldName"=>"身份证","fieldValue"=>$drive['sfcode']],
                ["docId"=>"40151231", "fieldId"=>"9639976114", "fieldName"=>"联系电话", "fieldValue"=>$user['user_tel']],
                ["docId"=>"40151231", "fieldId"=>"2971817883", "fieldName"=>"车辆名称", "fieldValue"=>$sku_info['name']],
                ["docId"=>"40151231", "fieldId"=>"6668460389", "fieldName"=>"车牌号", "fieldValue"=>$sku_info['carnum']],
                ["docId"=>"40151231", "fieldId"=>"5645699029", "fieldName"=>"年月日", "fieldValue"=>$year],
                ["docId"=>"40151231", "fieldId"=>"8687166359", "fieldName"=>"日租金", "fieldValue"=>$sku_info['money']],
                ["docId"=>"40151231", "fieldId"=>"8811886984", "fieldName"=>"天数", "fieldValue"=>$day_number],
                ["docId"=>"40151231", "fieldId"=>"9367428219", "fieldName"=>"总金额", "fieldValue"=>$total_price],
            ];

            $taskId = $res['data']['signTaskId'];
            $this->send('/sign-task/field/fill-values',[
                'signTaskId' => $taskId,
                'docFieldValues' => $signFields
            ]);

            //提交
            $this->send('/sign-task/start', [
                'signTaskId' => $taskId,
            ]);

            //更新订单表
            pdo_update('yzzc_sun_order',['fdd_task_id'=>$taskId],['id'=>$order_id]);

            $this->return_msg(1,$res['data']);
        } catch (\Throwable $exception) {
            $this->return_msg(-1,[],$exception->getMessage());
        }
    }

    /**
     * @return void
     * 获取参与方签署链接
     */
    public function doPagegetSignTaskLink()
    {
        global $_GPC,$_W;
        $taskId = $_GPC['task_id'];
        if (!isset($_GPC['redirectMiniAppUrl']) || !$_GPC['redirectMiniAppUrl']){
            $this->return_msg(-1,[],'回跳地址不能为空');
        }
        try {
            $res = $this->send('/sign-task/actor/get-url', [
                'signTaskId' => $taskId,
                'actorId' => '承租方',
                'redirectMiniAppUrl' => urlencode($_GPC['redirectMiniAppUrl'])
            ]);
            $this->return_msg(1,$res['data']);
        } catch (\Throwable $exception) {
            $this->return_msg(-1,[],$exception->getMessage());
        }
    }

    /**
     * 获取签署任务预览链接
     */
    public function doPagegetPreviewSignTaskLink()
    {
        global $_GPC;
        $taskId = $_GPC['task_id'];

        try {
            $res = $this->send('/sign-task/get-preview-url', [
                'signTaskId' => $taskId,
            ]);
            $this->return_msg(1,$res['data']);
        } catch (\Throwable $exception) {
            $this->return_msg(-1,[],$exception->getMessage());
        }
    }


    /******************************************发票**********************************/

    /**
     * @return void
     * 开发票
     */
    public function doPagesubmitInvoice()
    {
        global $_GPC,$_W;
        $invoice_type = $_GPC['invoice_type'];
        $uid = $_GPC['uid'];
        $invoice = $_GPC['invoice'];
        $invoice_number = $_GPC['invoice_number'];
        $invoice_email = $_GPC['invoice_email'];
        $invoice_address = $_GPC['invoice_address'];
        $invoice_content = $_GPC['invoice_content'];
        $order_id = $_GPC['order_id'];
        $order_info = pdo_get('yzzc_sun_order',['id'=>$order_id]);
        if ($order_info['is_invoice'] == 1){
            $this->return_msg(1,'','该订单已经开过发票');
        }
        $user = pdo_get('yzzc_sun_user',['id'=>$uid]);
        $order_set = pdo_get('yzzc_sun_order_set',array("uniacid" => $_W["uniacid"]), array("invoice_rate",'invoice_postage'));
        $invoice_money = sprintf("%.2f",$order_info['prepay_money'] * ($order_set['invoice_rate'] / 100));
        $total_count = $invoice_money + $order_set['invoice_postage'];
        $out_trade_no = rand(10000, 99999) . time() . rand(10000, 99999) . $order_id;
        $data = [
            'invoice_type' => $invoice_type,
            'invoice' => $invoice,
            'invoice_number' => $invoice_number,
            'invoice_money' => $invoice_money,
            'invoice_postage' => $order_set['invoice_postage'],
            'invoice_email' => $invoice_email,
            'invoice_address' => $invoice_address,
            'invoice_content' => $invoice_content,
            'invoice_out_no' => 0,
        ];
        if ($total_count <= 0){
            $data['is_invoice'] = 1;
            $data['invoice_pay_status'] = 2;
        }

        $result = pdo_update('yzzc_sun_order',$data,['id'=>$order_id]);
        if (!$result){
            $this->return_msg(-1, [],'开票失败');
        }
        if ($total_count > 0){
            //支付金额大于0 ，请求支付
            $appData = pdo_get("yzzc_sun_system", array("uniacid" => $_W["uniacid"]));
            $appid = $appData["appid"];
            $mch_id = $appData["mchid"];
            $key = $appData["wxkey"];
            $openid = $user["openid"];
            $total_fee = $total_count * 100;

            $body = "订单开票费用";
            $notify_url = $_W["siteroot"] . "addons/yzzc_sun/notify.php";

            //4 支付开票费用
            $attach = $_W["uniacid"] . "@@@4@@@" . $order_id;
            include_once "wxpay.php";
            $wxpay = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $attach, $notify_url);

            $ret = $wxpay->pay();
            $ret['order_id'] = $order_id;
            $ret['is_pay'] = 1;
            $this->return_msg(1, $ret);
        }else{
            $this->return_msg(1, ['is_pay'=>0],'开票成功');
        }
    }

    /**
     * @return void
     * 发票金额计算
     */
    public function doPageorderInvoiceTotal()
    {
        global $_GPC,$_W;
        $order_id = $_GPC['order_id'];
        $order_info = pdo_get('yzzc_sun_order',['id'=>$order_id]);
        if ($order_info['is_invoice'] == 1){
            $this->return_msg(1,'','该订单已经开过发票');
        }
        $order_set = pdo_get('yzzc_sun_order_set',array("uniacid" => $_W["uniacid"]), array("invoice_rate",'invoice_postage'));
        $invoice_money = $order_info['prepay_money'] * ($order_set['invoice_rate'] / 100);
        $invoice_money = sprintf("%.2f",$invoice_money);
        $ret = [
            'invoice_money' => $invoice_money,
            'invoice_postage' => $order_set['invoice_rate']
        ];
        $this->return_msg(1, $ret);

    }

    /**
     * @return void
     * 订单列表
     */
    public function doPageOrderInvoiceList()
    {
        global $_GPC, $_W;
        $page = $_GPC["page"] ? $_GPC["page"] : 1;
        $length = $_GPC["length"] ? $_GPC["length"] : 10;

        $where = ["uniacid" => $_W["uniacid"], "uid" => $_GPC["uid"], "display" => 1,'status'=>0];
        //优惠劵订单
        if (isset($_GPC['coupon_id']) && $_GPC['coupon_id'] == 1){
            $where['coupon >'] = 0;
        }

        //发票
        if (isset($_GPC['is_invoice'])){
            $where['is_invoice'] = $_GPC['is_invoice'];
        }
        $res = pdo_getall("yzzc_sun_order",$where, array('id','cid','sku_id','carnum','gettype','start_time','end_time','day','ordernum','ispay','total_money','status','start_shop','end_shop','user_address','user_lat','user_lng','is_invoice','invoice_type','invoice_pay_status','invoice_pay_time','invoice','invoice_number','invoice_money','invoice_postage','invoice_email','invoice_address','invoice_content'), '', array("status asc", "createtime desc"), array($page, $length));
        foreach ($res as $key => $val) {
            $car_info = pdo_get("yzzc_sun_goods_sku", array("id" => $val["sku_id"]),['id','sid','name','structure','grarbox','pic','cartype','displacement']);
            if ($car_info['cartype']){
                $cartype = pdo_get('yzzc_sun_cartype',['uniacid'=>$_W['uniacid'],'id'=>$car_info['cartype']]);
                $car_info['car_type_name'] = $cartype['name'] ?? '';
            }
            $res[$key]["carinfo"] = $car_info;
        }
        $this->return_msg(1, $res, "success");
    }

}